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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import re
|
3 |
+
from transformers import pipeline
|
4 |
+
from audio_recorder_streamlit import audio_recorder
|
5 |
+
import numpy as np
|
6 |
+
from scipy.io import wavfile
|
7 |
+
from io import BytesIO
|
8 |
+
import openai
|
9 |
+
from transformers import SpeechT5Processor, SpeechT5HifiGan, SpeechT5ForTextToSpeech
|
10 |
+
from datasets import load_dataset
|
11 |
+
import torch
|
12 |
+
from IPython.display import Audio
|
13 |
+
import os
|
14 |
+
import base64
|
15 |
+
import pandas as pd
|
16 |
+
|
17 |
+
st.set_page_config(layout='wide', page_title = "TalkGPT 🎤")
|
18 |
+
with open("style.css")as f:
|
19 |
+
st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html = True)
|
20 |
+
|
21 |
+
def add_bg(image_file):
|
22 |
+
with open(image_file, "rb") as image_file:
|
23 |
+
encoded_string = base64.b64encode(image_file.read())
|
24 |
+
st.markdown(
|
25 |
+
f"""
|
26 |
+
<style>
|
27 |
+
.stApp {{
|
28 |
+
background-image: url(data:image/{"png"};base64,{encoded_string.decode()});
|
29 |
+
background-size: cover;}}
|
30 |
+
}}
|
31 |
+
</style>
|
32 |
+
""",
|
33 |
+
unsafe_allow_html=True
|
34 |
+
)
|
35 |
+
|
36 |
+
#add_bg("ai.png")
|
37 |
+
|
38 |
+
checkpoint_stt = "openai/whisper-small.en"
|
39 |
+
checkpoint_tts = "microsoft/speecht5_tts"
|
40 |
+
checkpoint_vocoder = "microsoft/speecht5_hifigan"
|
41 |
+
dataset_tts = "Matthijs/cmu-arctic-xvectors"
|
42 |
+
|
43 |
+
@st.cache_resource()
|
44 |
+
def models():
|
45 |
+
stt_model = pipeline("automatic-speech-recognition", model=checkpoint_stt)
|
46 |
+
processor = SpeechT5Processor.from_pretrained(checkpoint_tts)
|
47 |
+
tts_model = SpeechT5ForTextToSpeech.from_pretrained(checkpoint_tts)
|
48 |
+
vocoder = SpeechT5HifiGan.from_pretrained(checkpoint_vocoder)
|
49 |
+
|
50 |
+
return stt_model, processor, vocoder, tts_model
|
51 |
+
|
52 |
+
stt_model, processor, vocoder, tts_model = models()
|
53 |
+
|
54 |
+
with st.sidebar:
|
55 |
+
st.title('Settings')
|
56 |
+
if 'OPENAI_API_TOKEN' in st.secrets:
|
57 |
+
st.success('API key already provided!', icon='✅')
|
58 |
+
openai_api_key = st.secrets['OPENAI_API_TOKEN']
|
59 |
+
else:
|
60 |
+
openai_api_key = st.text_input('Enter OpenAI API token:', type='password')
|
61 |
+
if not (openai_api_key).startswith('sk-') or len(openai_api_key) != 51:
|
62 |
+
st.warning('Please enter your credentials!', icon='⚠️')
|
63 |
+
else:
|
64 |
+
st.success('Proceed to entering your prompt message!', icon='👉')
|
65 |
+
|
66 |
+
st.markdown("<h3 style='text-align: left; color: white;'>Parameters</h3>", unsafe_allow_html=True)
|
67 |
+
st.markdown("<h5 style='text-align: left; color: white;'>Choose your parameters below.</h5>", unsafe_allow_html=True)
|
68 |
+
|
69 |
+
selected_model = st.selectbox('Choose a GPT model', ['GPT 3.5', 'GPT 4'], index = 1)
|
70 |
+
if selected_model == 'GPT 3.5':
|
71 |
+
llm = 'gpt-3.5-turbo'
|
72 |
+
elif selected_model == 'GPT 4':
|
73 |
+
llm = 'gpt-4'
|
74 |
+
temp = st.number_input('Temperature', min_value=0.01, max_value=4.0, value=0.1, step=0.01)
|
75 |
+
top_percent = st.number_input('Top Percent', min_value=0.01, max_value=1.0, value=0.9, step=0.01)
|
76 |
+
input_format = st.selectbox("Choose an input format", ["Text", "Audio"], index = 0)
|
77 |
+
audio_output = st.selectbox("Do you want audio output?", ["Yes", "No"], index = 0)
|
78 |
+
if audio_output == "Yes":
|
79 |
+
gender_select = st.selectbox("Choose the gender of your speaker", ["Male", "Female"], index = 1)
|
80 |
+
|
81 |
+
openai.api_key = openai_api_key
|
82 |
+
|
83 |
+
@st.cache_data()
|
84 |
+
def speech_embed():
|
85 |
+
embeddings_dataset = load_dataset(dataset_tts, split="validation")
|
86 |
+
embeddings_dataset = embeddings_dataset.to_pandas()
|
87 |
+
if gender_select == "Male":
|
88 |
+
#torch.tensor(list(embded[embded["filename"]=="cmu_us_bdl_arctic-wav-arctic_a0009"]["xvector"]))
|
89 |
+
embed_use = torch.tensor(list(embeddings_dataset[embeddings_dataset["filename"]=="cmu_us_bdl_arctic-wav-arctic_a0009"]["xvector"]))
|
90 |
+
elif gender_select == "Female":
|
91 |
+
embed_use = torch.tensor(list(embeddings_dataset[embeddings_dataset["filename"]=="cmu_us_clb_arctic-wav-arctic_a0144"]["xvector"]))
|
92 |
+
return embed_use
|
93 |
+
|
94 |
+
speaker_embeddings = speech_embed()
|
95 |
+
|
96 |
+
|
97 |
+
st.markdown("<h1 style='text-align: center; color: gold;'>TalkGPT 🎤</h1>", unsafe_allow_html=True)
|
98 |
+
st.markdown("<h3 style='text-align: center; color: white;'>Welcome to TalkGPT. You can speak to GPT and it will speak back to you.</h3>", unsafe_allow_html=True)
|
99 |
+
|
100 |
+
with st.expander("Click to see instructions on how the parameters/settings work"):
|
101 |
+
st.markdown("<h8 style='text-align: center; color: white;'>**Enter OpenAI API token**: You can create an OpenAI token [here](https://openai.com/) or learn how to create one by watching this [video](https://www.youtube.com/watch?v=EQQjdwdVQ-M)</h8>", unsafe_allow_html=True)
|
102 |
+
st.markdown("<h8 style='text-align: center; color: white;'>**Choose a GPT model**: You can use this parameter to choose between GPT 3.5 and GPT 4.</h8>", unsafe_allow_html=True)
|
103 |
+
st.markdown("<h8 style='text-align: center; color: white;'>**Temperature**: You can change this value to transform the creativity of GPT. A high temperature will make GPT too creative to the point that it produces meaningless statements. A very low temperature makes GPT repetitive.</h8>", unsafe_allow_html=True)
|
104 |
+
st.markdown("<h8 style='text-align: center; color: white;'>**Top Percent**: This is used to select the top n percent of the predicted next word. This can serve as a way to ensure GPT is likely going to produce words that matter.</h8>", unsafe_allow_html=True)
|
105 |
+
st.markdown("<h8 style='text-align: center; color: white;'>**Choose an input format**: You can select between text and audio. If you choose audio, you will have to speak into an audio recorder and if you choose text you will type in your question for GPT.</h8>", unsafe_allow_html=True)
|
106 |
+
st.markdown("<h8 style='text-align: center; color: white;'>**Do you want an audio output?**: If you select yes, you will get an audio response from GPT alongside the text response.</h8>", unsafe_allow_html=True)
|
107 |
+
st.markdown("<h8 style='text-align: center; color: white;'>**Choose the gender of your speaker**: You can select the gender of your speaker to be a male or female.</h8>", unsafe_allow_html=True)
|
108 |
+
|
109 |
+
def tts(input):
|
110 |
+
inputs = processor(text=input, return_tensors="pt")
|
111 |
+
with torch.no_grad():
|
112 |
+
speech = tts_model.generate_speech(inputs["input_ids"], speaker_embeddings, vocoder=vocoder).cpu().numpy()
|
113 |
+
|
114 |
+
return speech
|
115 |
+
|
116 |
+
def generate_llm_response():
|
117 |
+
|
118 |
+
use_messages = []
|
119 |
+
for i in range(len(st.session_state.messages)):
|
120 |
+
use_messages.append({"role": st.session_state.messages[i]["role"], "content": st.session_state.messages[i]["content"]})
|
121 |
+
|
122 |
+
response = openai.ChatCompletion.create(
|
123 |
+
model=llm,
|
124 |
+
messages=use_messages,
|
125 |
+
temperature = temp,
|
126 |
+
top_p = top_percent,
|
127 |
+
)
|
128 |
+
return response["choices"][0]["message"]["content"]
|
129 |
+
|
130 |
+
|
131 |
+
if "messages" not in st.session_state.keys():
|
132 |
+
st.session_state.messages = []
|
133 |
+
initial_system = {"role": "system", "content": "You are a helpful assistant.", "audio":""}
|
134 |
+
st.session_state.messages.append(initial_system)
|
135 |
+
initial_message = {"role": "assistant", "content": "How may I assist you today?", "audio":""}
|
136 |
+
st.session_state.messages.append(initial_message)
|
137 |
+
|
138 |
+
with st.chat_message(st.session_state.messages[1]["role"]):
|
139 |
+
st.write(st.session_state.messages[1]["content"])
|
140 |
+
tts_init1, sampling_rate = tts(st.session_state.messages[1]["content"]), 16000
|
141 |
+
st.audio(tts_init1, format='audio/wav', sample_rate=sampling_rate)
|
142 |
+
|
143 |
+
def message_output(message):
|
144 |
+
if message["role"] == "user":
|
145 |
+
with st.chat_message(message["role"]):
|
146 |
+
st.write(message["content"])
|
147 |
+
if message["role"] == "assistant":
|
148 |
+
with st.chat_message("assistant"):
|
149 |
+
use_response = message["content"]
|
150 |
+
placeholder = st.empty()
|
151 |
+
full_response = ''
|
152 |
+
for item in use_response:
|
153 |
+
full_response += item
|
154 |
+
placeholder.markdown(full_response)
|
155 |
+
placeholder.markdown(full_response)
|
156 |
+
|
157 |
+
if audio_output == "Yes":
|
158 |
+
if len(message["audio"]) > 100:
|
159 |
+
st.audio(message["audio"], format = "audio/wav", sample_rate=16000)
|
160 |
+
else:
|
161 |
+
for i in range(len(message["audio"])):
|
162 |
+
response_no = "Output " + str(i + 1)
|
163 |
+
st.text(response_no)
|
164 |
+
st.audio(message["audio"][i], format='audio/wav', sample_rate=16000)
|
165 |
+
else:
|
166 |
+
st.text("No Audio Output.")
|
167 |
+
|
168 |
+
if input_format == "Text":
|
169 |
+
if prompt := st.chat_input("Text Me", disabled=not openai_api_key):
|
170 |
+
new_message = {"role": "user", "content": prompt, "audio":""}
|
171 |
+
#with st.chat_message(new_message["role"]):
|
172 |
+
# st.write(new_message["content"])
|
173 |
+
st.session_state.messages.append(new_message)
|
174 |
+
|
175 |
+
elif input_format == "Audio":
|
176 |
+
with st.sidebar:
|
177 |
+
st.text("Click to Record")
|
178 |
+
audio_bytes = audio_recorder(text="",
|
179 |
+
recording_color="#e8b62c",
|
180 |
+
neutral_color="#6aa36f",
|
181 |
+
icon_name="microphone",
|
182 |
+
icon_size="6x",
|
183 |
+
sample_rate = 16000)
|
184 |
+
if audio_bytes:
|
185 |
+
|
186 |
+
bytes_io = BytesIO(audio_bytes)
|
187 |
+
|
188 |
+
sample_rate, audio_data = wavfile.read(bytes_io)
|
189 |
+
|
190 |
+
audio_input = {"array": audio_data[:,0].astype(np.float32)*(1/32768.0),
|
191 |
+
"sampling_rate": 16000}
|
192 |
+
text = str(stt_model(audio_input)["text"])
|
193 |
+
new_message = {"role": "user", "content": text, "audio":""}
|
194 |
+
#with st.chat_message(new_message["role"]):
|
195 |
+
# st.write(new_message["content"])
|
196 |
+
st.session_state.messages.append(new_message)
|
197 |
+
|
198 |
+
for message in st.session_state.messages[2:]:
|
199 |
+
message_output(message)
|
200 |
+
|
201 |
+
if st.session_state.messages[-1]["role"] != "assistant":
|
202 |
+
with st.chat_message("assistant"):
|
203 |
+
with st.spinner("Thinking..."):
|
204 |
+
response = generate_llm_response()
|
205 |
+
placeholder = st.empty()
|
206 |
+
full_response = ''
|
207 |
+
for item in response:
|
208 |
+
full_response += item
|
209 |
+
placeholder.markdown(full_response)
|
210 |
+
placeholder.markdown(full_response)
|
211 |
+
new_message = {"role": "assistant", "content": full_response}
|
212 |
+
if audio_output == "Yes":
|
213 |
+
if (len(full_response)) >= 500:
|
214 |
+
word = full_response
|
215 |
+
tot = 0
|
216 |
+
collect_response = []
|
217 |
+
reuse_words = ""
|
218 |
+
next_word = word
|
219 |
+
while tot < len(word):
|
220 |
+
new_word = next_word[:500]
|
221 |
+
good_word = new_word[:len(new_word) - new_word[::-1].find(".")]
|
222 |
+
collect_response.append(good_word)
|
223 |
+
reuse_words += good_word
|
224 |
+
tot += len(good_word)
|
225 |
+
next_word = word[tot:]
|
226 |
+
#new_word = next_word[:500]
|
227 |
+
#ind = []
|
228 |
+
#for match in re.finditer(r' ', new_word[::-1]):
|
229 |
+
# ind.append(match.start())
|
230 |
+
#if len(ind) > 1:
|
231 |
+
# good_word = new_word[:len(new_word) - ind[1]]
|
232 |
+
# use_word = new_word[:len(new_word)]
|
233 |
+
#else:
|
234 |
+
# good_word = new_word[:len(new_word)]
|
235 |
+
# use_word = new_word[:len(new_word)]
|
236 |
+
#collect_response.append(use_word)
|
237 |
+
#reuse_words += good_word
|
238 |
+
#tot += len(good_word)
|
239 |
+
#next_word = word[tot:]
|
240 |
+
|
241 |
+
#collect_response[-2] = collect_response[-2] + collect_response[-1]
|
242 |
+
#collect_response = collect_response[:-1]
|
243 |
+
tts_list = []
|
244 |
+
for i in range(len(collect_response)):
|
245 |
+
response_no = "Output " + str(i + 1)
|
246 |
+
st.text(response_no)
|
247 |
+
tts_output, sampling_rate = tts(collect_response[i]), 16000
|
248 |
+
tts_list.append(tts_output)
|
249 |
+
st.audio(tts_output, format='audio/wav', sample_rate=sampling_rate)
|
250 |
+
new_message["audio"] = tts_list
|
251 |
+
else:
|
252 |
+
tts_output, sampling_rate = tts(full_response), 16000
|
253 |
+
new_message["audio"] = tts_output
|
254 |
+
st.audio(tts_output, format='audio/wav', sample_rate=sampling_rate)
|
255 |
+
else:
|
256 |
+
st.text("No Audio Output.")
|
257 |
+
new_message["audio"] = ""
|
258 |
+
|
259 |
+
st.session_state.messages.append(new_message)
|
260 |
+
|
261 |
+
def clear_chat_history():
|
262 |
+
st.session_state.messages = []
|
263 |
+
audio_list = []
|
264 |
+
initial_system = {"role": "system", "content": "You are a helpful assistant.", "audio":""}
|
265 |
+
st.session_state.messages.append(initial_system)
|
266 |
+
initial_message = {"role": "assistant", "content": "How may I assist you today?", "audio":""}
|
267 |
+
st.session_state.messages.append(initial_message)
|
268 |
+
|
269 |
+
st.sidebar.button('Clear Chat History', on_click=clear_chat_history)
|
requirements.txt
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
streamlit==1.26.0
|
3 |
+
audio-recorder-streamlit
|
4 |
+
transformers
|
5 |
+
openai
|
6 |
+
torch
|
7 |
+
numpy
|
8 |
+
scipy
|
9 |
+
langchain
|
10 |
+
tabulate
|
11 |
+
datasets[audio]
|
12 |
+
sentencepiece
|
13 |
+
IPython
|
14 |
+
torchaudio
|
style.css
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
header.css-1avcm0n {
|
2 |
+
background-color: rgba(0,0,0,0);
|
3 |
+
}
|
4 |
+
|
5 |
+
div.css-usj992 {
|
6 |
+
background-color: rgba(0,0,0,0)
|
7 |
+
}
|
8 |
+
|
9 |
+
div.css-10oheav {
|
10 |
+
background-color: rgba(0,0,0,0)
|
11 |
+
}
|
12 |
+
|
13 |
+
svg.css-fblp2m {
|
14 |
+
background-color: rgba(60,60,60,0)
|
15 |
+
}
|