Hamxa1997 commited on
Commit
f79ca48
·
verified ·
1 Parent(s): b0f4059

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +285 -0
app.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import whisper
4
+ import torch
5
+ from gtts import gTTS
6
+ import IPython.display as ipd
7
+ from sentence_transformers import SentenceTransformer
8
+ import faiss
9
+ import pandas as pd
10
+ from datasets import load_dataset
11
+ from deep_translator import GoogleTranslator
12
+ from langdetect import detect
13
+ from groq import Groq # Correct import for Groq API
14
+
15
+ # Set up Whisper with a smaller model or on CPU
16
+ model_name = "small" # Use "small", "base", or "medium" for smaller models
17
+ whisper_model = whisper.load_model(model_name)
18
+ device = "cuda" if torch.cuda.is_available() else "cpu"
19
+ whisper_model.to(device)
20
+
21
+ # Initialize the GoogleTranslator from deep-translator
22
+ translator = GoogleTranslator(source='auto', target='en')
23
+
24
+ # Load and prepare the dataset for retrieval
25
+ dataset = load_dataset("qgyd2021/e_commerce_customer_service", "faq")
26
+ train_dataset = dataset['train']
27
+
28
+ # Initialize the SentenceTransformer model
29
+ embedder = SentenceTransformer('paraphrase-MiniLM-L6-v2')
30
+
31
+ # Encode the questions from the dataset and set up FAISS
32
+ dataset_embeddings = embedder.encode(train_dataset['question'], convert_to_tensor=True)
33
+ index = faiss.IndexFlatL2(dataset_embeddings.shape[1]) # Create an index based on L2 distance
34
+ index.add(dataset_embeddings.cpu().numpy()) # Add the embeddings to the index
35
+
36
+ # Set up Groq API with direct API key
37
+
38
+ client = Groq(api_key=api_key)
39
+ import torch
40
+ from transformers import pipeline
41
+ from langdetect import detect
42
+ from deep_translator import GoogleTranslator
43
+ from gtts import gTTS
44
+
45
+ # Initialize the sentiment analysis pipeline
46
+ device = 0 if torch.cuda.is_available() else -1
47
+ try:
48
+ sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english", device=device)
49
+ except Exception as e:
50
+ print(f"Error loading sentiment analysis model: {e}")
51
+
52
+ # Function to detect the language
53
+ def detect_language(text):
54
+ try:
55
+ return detect(text)
56
+ except Exception as e:
57
+ print(f"Error during language detection: {e}")
58
+ return "en" # Default to English if detection fails
59
+
60
+ # Translate text using deep-translator
61
+ def translate_text(text, dest_lang):
62
+ try:
63
+ return GoogleTranslator(source='auto', target=dest_lang).translate(text)
64
+ except Exception as e:
65
+ print(f"Error during translation: {e}")
66
+ return text # Return original text if translation fails
67
+
68
+ # Function to generate a greeting based on sentiment
69
+ def generate_greeting(sentiment, lang):
70
+ try:
71
+ if sentiment == 'NEGATIVE':
72
+ if lang in ['ur', 'hi']:
73
+ return "پریشان نہ ہوں، میں آپ کی مدد کے لئے یہاں ہوں."
74
+ else:
75
+ return "Please don't be sad, I'm here to solve your problem."
76
+ elif sentiment == 'NEUTRAL':
77
+ if lang in ['ur', 'hi']:
78
+ return "آپ کا مسئلہ حل کرتے ہیں، آپ فکر نہ کریں."
79
+ else:
80
+ return "I understand your concern, let's get that sorted out."
81
+ elif sentiment == 'POSITIVE':
82
+ if lang in ['ur', 'hi']:
83
+ return "یہ خوشی کی بات ہے کہ آپ خوش ہیں! آئیں، ہم اسے بہتر بناتے ہیں."
84
+ else:
85
+ return "I'm glad you're feeling positive! Let's make things even better."
86
+ else:
87
+ if lang in ['ur', 'hi']:
88
+ return "ہیلو! میں آج تمہاری مدد کیسے کر سکتا ہوں؟"
89
+ else:
90
+ return "Hello! How can I assist you today?"
91
+ except Exception as e:
92
+ print(f"Error generating greeting: {e}")
93
+ return "Hello!"
94
+
95
+ # Function to transcribe audio using Whisper
96
+ def transcribe_audio(audio_path):
97
+ try:
98
+ result = whisper_model.transcribe(audio_path)
99
+ transcription = result['text']
100
+ print(f"Transcription result: {transcription}")
101
+ return transcription
102
+ except Exception as e:
103
+ print(f"Error during transcription: {e}")
104
+ return "Error during transcription"
105
+
106
+ # Function to generate a chatbot response based on transcription
107
+ def generate_chatbot_response(transcription):
108
+ try:
109
+ # Detect language of the transcription
110
+ detected_language = detect_language(transcription)
111
+
112
+ # Translate to English if necessary
113
+ if detected_language in ['ur', 'hi']:
114
+ transcription = translate_text(transcription, 'en')
115
+
116
+ # Perform sentiment analysis
117
+ sentiment_result = sentiment_analyzer(transcription)[0]
118
+ sentiment = sentiment_result['label'].upper()
119
+
120
+ # Generate a greeting based on sentiment
121
+ greeting = generate_greeting(sentiment, detected_language)
122
+
123
+ # Retrieve relevant context using FAISS
124
+ transcription_embedding = embedder.encode([transcription], convert_to_tensor=True)
125
+ _, indices = index.search(transcription_embedding.cpu().numpy(), k=1)
126
+ best_match_index = indices[0][0]
127
+ context = train_dataset['answer'][best_match_index]
128
+ url = train_dataset['url'][best_match_index]
129
+
130
+ # Generate the full response
131
+ response = f"{greeting}\n\n{context}\n\nPlease visit this link for your query: {url}"
132
+
133
+ # Translate the response back to Urdu if necessary
134
+ if detected_language in ['ur', 'hi']:
135
+ response = translate_text(response, 'ur')
136
+
137
+ return response
138
+ except Exception as e:
139
+ print(f"Error during chatbot response generation: {e}")
140
+ return "Error during response generation"
141
+
142
+ # Function to convert text to speech using gTTS
143
+ def text_to_speech(text, lang='en'):
144
+ try:
145
+ tts = gTTS(text=text, lang=lang)
146
+ tts.save("response.mp3")
147
+ return "response.mp3"
148
+ except Exception as e:
149
+ print(f"Error during text-to-speech conversion: {e}")
150
+ return "Error during text-to-speech conversion"
151
+
152
+ # Main function for Gradio interface
153
+ def chatbot(text_input=None, audio_input=None):
154
+ if audio_input:
155
+ # Step 1: Transcribe audio to text if audio input is provided
156
+ transcription = transcribe_audio(audio_input)
157
+ input_text = transcription
158
+ else:
159
+ # Use the text input directly if provided
160
+ input_text = text_input
161
+
162
+ # Step 2: Generate a chatbot response based on the input text
163
+ response = generate_chatbot_response(input_text)
164
+
165
+ # Step 3: Convert the response text to speech if the original input was audio
166
+ if audio_input:
167
+ lang = 'ur' if detect_language(input_text) in ['ur', 'hi'] else 'en'
168
+ audio_path = text_to_speech(response, lang=lang)
169
+ return input_text, response, audio_path
170
+ else:
171
+ return input_text, response, None
172
+
173
+ # Custom CSS for styling the interface and buttons
174
+ custom_css = """
175
+ body {
176
+ font-family: 'Arial', sans-serif;
177
+ background-color: #1e1e1e; /* Black background */
178
+ color: white; /* White text */
179
+ }
180
+
181
+ h1 {
182
+ font-size: 36px;
183
+ color: white;
184
+ text-align: center;
185
+ margin-bottom: 20px;
186
+ }
187
+
188
+ h2 {
189
+ font-size: 24px;
190
+ color: white;
191
+ text-align: center;
192
+ margin-bottom: 10px;
193
+ }
194
+
195
+ .instructions {
196
+ font-size: 16px; /* Smaller font size for instructions */
197
+ color: #cccccc; /* Light gray color for instructions */
198
+ text-align: center;
199
+ margin-bottom: 20px;
200
+ }
201
+
202
+ .gradio-container {
203
+ background-color: #1e1e1e;
204
+ padding: 20px;
205
+ border-radius: 10px;
206
+ }
207
+
208
+ .gr-box {
209
+ border-radius: 5px;
210
+ border: 1px solid #333;
211
+ padding: 10px;
212
+ margin-bottom: 10px;
213
+ }
214
+
215
+ .gr-button {
216
+ border-radius: 5px;
217
+ padding: 10px;
218
+ font-weight: bold;
219
+ font-size: 16px;
220
+ transition: background-color 0.3s;
221
+ }
222
+
223
+ .gr-button-submit {
224
+ background-color: #28a745; /* Green submit button */
225
+ color: white;
226
+ }
227
+
228
+ .gr-button-submit:hover {
229
+ background-color: #218838;
230
+ }
231
+
232
+ .gr-button-clear {
233
+ background-color: #dc3545; /* Red clear button */
234
+ color: white;
235
+ }
236
+
237
+ .gr-button-clear:hover {
238
+ background-color: #c82333;
239
+ }
240
+
241
+ .gr-textbox, .gr-audio {
242
+ border-radius: 5px;
243
+ border: 1px solid #0056b3; /* Blue border */
244
+ padding: 8px;
245
+ background-color: #2e2e2e;
246
+ color: white;
247
+ }
248
+
249
+ .gr-textbox {
250
+ background-color: #0056b3; /* Blue background for textboxes */
251
+ color: white;
252
+ }
253
+
254
+ .gr-container {
255
+ max-width: 900px;
256
+ margin: auto;
257
+ }
258
+ """
259
+
260
+ import gradio as gr
261
+
262
+ # Gradio interface setup with updated CSS
263
+ with gr.Blocks(css=custom_css) as iface:
264
+ gr.Markdown("<h1>Multilingual Customer Service Chatbot</h1>")
265
+ gr.Markdown("<h2>Ask your questions</h2>")
266
+ gr.Markdown("<p class='instructions'>If you type in Urdu, it will respond in Urdu. If in English, it will respond in English. Same with voice.</p>")
267
+
268
+ with gr.Row():
269
+ with gr.Column():
270
+ text_input = gr.Textbox(lines=2, placeholder="Type your query here...", label="Text Input (Optional)")
271
+ audio_input = gr.Audio(type="filepath", label="Audio Input (Optional)")
272
+ with gr.Column():
273
+ transcription_output = gr.Textbox(label="Transcription") # Add transcription output
274
+ response_text = gr.Textbox(label="Chatbot Response")
275
+ response_audio = gr.Audio(label="Response Audio (if applicable)")
276
+
277
+ with gr.Row():
278
+ submit_btn = gr.Button("Submit", elem_id="submit-btn", variant="primary")
279
+ clear_btn = gr.Button("Clear", elem_id="clear-btn", variant="secondary")
280
+
281
+ submit_btn.click(chatbot, inputs=[text_input, audio_input], outputs=[transcription_output, response_text, response_audio])
282
+ clear_btn.click(lambda: (None, None, None, None, None), inputs=[], outputs=[text_input, audio_input, transcription_output, response_text, response_audio])
283
+
284
+ # Launch the Gradio interface
285
+ iface.launch()