File size: 10,868 Bytes
bc8b865
 
 
 
 
 
27f9093
bc8b865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27f9093
bc8b865
 
 
27f9093
 
 
bc8b865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1aff08b
bc8b865
 
 
27f9093
bc8b865
 
27f9093
bc8b865
27f9093
bc8b865
 
 
 
1aff08b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc8b865
 
 
 
 
 
 
 
 
1aff08b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# import whisper
# import os
# from gtts import gTTS
# import gradio as gr
# from groq import Groq
# from datetime import datetime
# import tempfile

# # Load a smaller Whisper model for faster processing
# try:
#     model = whisper.load_model("tiny")
# except Exception as e:
#     print(f"Error loading Whisper model: {e}")
#     model = None

# # Set up Groq API client using environment variable
# GROQ_API_TOKEN = os.getenv("GROQ_API")
# if not GROQ_API_TOKEN:
#     raise ValueError("Groq API token is missing. Set 'GROQ_API' in your environment variables.")
# client = Groq(api_key=GROQ_API_TOKEN)

# # Initialize the chat history
# chat_history = []

# # Function to get the LLM response from Groq with timeout handling
# def get_llm_response(user_input, role="detailed responder"):
#     prompt = f"As an expert, provide a detailed and knowledgeable response: {user_input}" if role == "expert" else \
#              f"As a good assistant, provide a clear, concise, and helpful response: {user_input}" if role == "good assistant" else \
#              f"Provide a thorough and detailed response: {user_input}"

#     try:
#         chat_completion = client.chat.completions.create(
#             messages=[{"role": "user", "content": user_input}],
#             model="llama3-8b-8192",  # Replace with your desired model
#             timeout=20  # Increased timeout to 20 seconds
#         )
#         return chat_completion.choices[0].message.content
#     except Exception as e:
#         print(f"Error during LLM response retrieval: {e}")
#         return "Sorry, there was an error retrieving the response. Please try again."

# # Function to convert text to speech using gTTS and handle temporary files
# def text_to_speech(text):
#     try:
#         tts = gTTS(text)
#         with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_file:
#             output_audio = temp_file.name
#             tts.save(output_audio)
#         return output_audio
#     except Exception as e:
#         print(f"Error generating TTS: {e}")
#         return None

# # Main chatbot function to handle audio input and output with chat history
# def chatbot(audio):
#     if not model:
#         return "Error: Whisper model is not available.", None, chat_history

#     if not audio:
#         return "No audio provided. Please upload a valid audio file.", None, chat_history

#     try:
#         # Step 1: Transcribe the audio using Whisper
#         result = model.transcribe(audio)
#         user_text = result.get("text", "")
#         if not user_text.strip():
#             return "Could not understand the audio. Please try speaking more clearly.", None, chat_history

#         # Get current timestamp
#         timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

#         # Display transcription in chat history
#         chat_history.append((timestamp, "User", user_text))

#         # Step 2: Get LLM response from Groq
#         response_text = get_llm_response(user_text)

#         # Step 3: Convert the response text to speech
#         output_audio = text_to_speech(response_text)

#         # Append the latest interaction to the chat history
#         chat_history.append((timestamp, "Chatbot", response_text))

#         # Format the chat history for display with timestamps and clear labels
#         formatted_history = "\n".join([f"[{time}] {speaker}: {text}" for time, speaker, text in chat_history])
        
#         return formatted_history, output_audio, chat_history

#     except Exception as e:
#         print(f"Error in chatbot function: {e}")
#         return "Sorry, there was an error processing your request.", None, chat_history

# # Gradio interface for real-time interaction with chat history display
# iface = gr.Interface(
#     fn=chatbot,
#     inputs=gr.Audio(type="filepath"),
#     outputs=[
#         gr.Textbox(label="Chat History", lines=10, interactive=False),  # Display chat history
#         gr.Audio(type="filepath", label="Response Audio"),
#     ],
#     live=True,
#     title="Voice to Voice Chatbot",
#     description="Upload your audio, and the chatbot will transcribe and respond to it with a synthesized response.",
#     theme="default",
#     css=''' 
#         body {
#             background-image: url("https://huggingface.co/spaces/abdullahzunorain/voice-to-voice-Chatbot/resolve/main/BG_1.jpg");
#             background-size: cover;
#             background-position: center;
#             background-repeat: no-repeat;
#             color: white;
#             font-family: 'Helvetica Neue', sans-serif;
#         }
#         .gradio-container {
#             background-color: rgba(0, 0, 0, 0.7);
#             padding: 20px;
#             border-radius: 10px;
#             box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
#         }
#         h1, h2, p, .gradio-label {
#             color: #FFD700;  /* Gold color for labels and titles */
#             text-align: center;
#         }
#         .gradio-button {
#             background-color: #FFD700;
#             color: black;
#             border-radius: 5px;
#             font-weight: bold;
#             transition: background-color 0.3s, transform 0.2s;
#         }
#         .gradio-button:hover {
#             background-color: #FFC107;  /* Lighter gold on hover */
#             transform: scale(1.05);
#         }
#         .gradio-input {
#             background-color: rgba(255, 255, 255, 0.9);
#             border-radius: 4px;
#             border: 2px solid #FFD700; /* Gold border */
#         }
#         .gradio-audio {
#             border: 2px solid #FFD700; /* Gold border for audio */
#         }
#     '''
# )

# # Launch the Gradio app
# if __name__ == "__main__":
#     iface.launch()










import whisper
import os
from gtts import gTTS
import gradio as gr
from groq import Groq
from datetime import datetime
import tempfile

# Load a smaller Whisper model for faster processing
try:
    model = whisper.load_model("tiny")
except Exception as e:
    print(f"Error loading Whisper model: {e}")
    model = None

# Set up Groq API client using environment variable
GROQ_API_TOKEN = os.getenv("GROQ_API")
if not GROQ_API_TOKEN:
    raise ValueError("Groq API token is missing. Set 'GROQ_API' in your environment variables.")
client = Groq(api_key=GROQ_API_TOKEN)

# Initialize the chat history
chat_history = []

# Function to get the LLM response from Groq with timeout handling
def get_llm_response(user_input, role="detailed responder"):
    prompt = f"As an expert, provide a detailed and knowledgeable response: {user_input}" if role == "expert" else \
             f"As a good assistant, provide a clear, concise, and helpful response: {user_input}" if role == "good assistant" else \
             f"Provide a thorough and detailed response: {user_input}"

    try:
        chat_completion = client.chat.completions.create(
            messages=[{"role": "user", "content": user_input}],
            model="llama3-8b-8192",  # Replace with your desired model
            timeout=20  # Increased timeout to 20 seconds
        )
        return chat_completion.choices[0].message.content
    except Exception as e:
        print(f"Error during LLM response retrieval: {e}")
        return "Sorry, there was an error retrieving the response. Please try again."

# Function to convert text to speech using gTTS and handle temporary files
def text_to_speech(text):
    try:
        tts = gTTS(text)
        with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_file:
            output_audio = temp_file.name
            tts.save(output_audio)
        return output_audio
    except Exception as e:
        print(f"Error generating TTS: {e}")
        return None

# Main chatbot function to handle audio input and output with chat history
def chatbot(audio):
    if not model:
        return "Error: Whisper model is not available.", None, chat_history

    if not audio:
        return "No audio provided. Please upload a valid audio file.", None, chat_history

    try:
        # Step 1: Transcribe the audio using Whisper
        result = model.transcribe(audio)
        user_text = result.get("text", "")
        if not user_text.strip():
            return "Could not understand the audio. Please try speaking more clearly.", None, chat_history

        # Get current timestamp
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # Display transcription in chat history
        chat_history.append((timestamp, "User", user_text))

        # Step 2: Get LLM response from Groq
        response_text = get_llm_response(user_text)

        # Step 3: Convert the response text to speech
        output_audio = text_to_speech(response_text)

        # Append the latest interaction to the chat history
        chat_history.append((timestamp, "Chatbot", response_text))

        # Format the chat history for display with timestamps and clear labels
        formatted_history = "\n".join([f"[{time}] {speaker}: {text}" for time, speaker, text in chat_history])
        
        return formatted_history, output_audio, chat_history

    except Exception as e:
        print(f"Error in chatbot function: {e}")
        return "Sorry, there was an error processing your request.", None, chat_history

# Gradio interface for real-time interaction with chat history display
iface = gr.Interface(
    fn=chatbot,
    inputs=gr.Audio(type="filepath"),
    outputs=[
        gr.Textbox(label="Chat History"),  # Display chat history
        gr.Audio(type="filepath", label="Response Audio"),
    ],
    live=True,
    title="Voice to Voice Chatbot",
    description="Upload your audio, and the chatbot will transcribe and respond to it with a synthesized response.",
    theme="default",
    css=''' 
        body {
            background-image: url("https://huggingface.co/spaces/abdullahzunorain/voice-to-voice-Chatbot/resolve/main/BG_1.jpg");
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            color: white;
            font-family: Arial, sans-serif;
        }
        # .gradio-container {
        #     background-color: rgba(0, 0, 0, 0.6);
        #     padding: 20px;
        #     border-radius: 8px;
        #     box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        # }
        # h1, h2, p, .gradio-label {
        #     color: #FFD700;  /* Gold color for labels and titles */
        # }
        # .gradio-button {
        #     background-color: #FFD700;
        #     color: black;
        #     border-radius: 4px;
        #     font-weight: bold;
        # }
        # .gradio-input {
        #     background-color: rgba(255, 255, 255, 0.9);
        #     border-radius: 4px;
        # }
    '''
)

# Launch the Gradio app
if __name__ == "__main__":
    iface.launch()