AnasAlokla commited on
Commit
6dfb995
Β·
verified Β·
1 Parent(s): 87a1ca5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -115
app.py CHANGED
@@ -54,7 +54,45 @@ SUPPORTED_LANGUAGES = {
54
  'tr': 'Turkish'
55
  }
56
 
57
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  def detect_language(text):
60
  """Detect the language of the input text."""
@@ -165,54 +203,69 @@ def load_emotion_classifier(model_name):
165
  try:
166
  # Use the HF token if available for authentication
167
  if hf_token:
168
- return pipeline("text-classification", model=model_name, use_auth_token=hf_token,top_k=None)
169
  else:
170
- return pipeline("text-classification", model=model_name,top_k=None)
171
  except Exception as e:
172
  st.error(f"Error loading model {model_name}: {str(e)}")
173
  return None
174
 
175
  def get_ai_response(user_input, emotion_predictions, detected_language):
176
  """Generates AI response based on user input, detected emotions, and language."""
177
- dominant_emotion = None
178
- max_score = 0
179
-
180
- for prediction in emotion_predictions:
181
- if prediction['score'] > max_score:
182
- max_score = prediction['score']
183
- dominant_emotion = prediction['label']
184
-
185
- if dominant_emotion is None:
186
- return "Error: No emotion detected for response generation."
187
-
188
- # Create enhanced prompt with language and emotion context
189
- prompt_text = create_enhanced_prompt(dominant_emotion, user_input, detected_language, max_score)
190
- response = generate_text(prompt_text)
 
 
 
 
 
 
191
 
192
- return response
 
 
193
 
194
  def display_top_predictions(emotion_predictions, selected_language, num_predictions=3):
195
  """Display top emotion predictions in sidebar."""
196
- # Sort predictions by score in descending order
197
- sorted_predictions = sorted(emotion_predictions, key=lambda x: x['score'], reverse=True)
198
-
199
- # Take top N predictions
200
- top_predictions = sorted_predictions[:num_predictions]
201
-
202
- # Display in sidebar
203
- st.sidebar.markdown("---")
204
- st.sidebar.subheader("🎯 Top Emotion Predictions")
205
-
206
- for i, prediction in enumerate(top_predictions, 1):
207
- emotion = prediction['label']
208
- score = prediction['score']
209
- percentage = score * 100
210
 
211
- # Create a progress bar for visual representation
212
- st.sidebar.markdown(f"**{i}. {emotion.title()}**")
213
- st.sidebar.progress(score)
214
- st.sidebar.markdown(f"Score: {percentage:.1f}%")
215
  st.sidebar.markdown("---")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
  def display_language_info(detected_language, confidence_scores=None):
218
  """Display detected language information."""
@@ -258,17 +311,7 @@ def main():
258
  )
259
 
260
  # Language detection settings
261
- #st.sidebar.markdown("---")
262
- #st.sidebar.subheader("πŸ” Language Detection")
263
- #auto_detect = st.sidebar.checkbox("Auto-detect input language", value=True)
264
- auto_detect=True
265
- #if not auto_detect:
266
- # manual_language = st.sidebar.selectbox(
267
- # "Select input language manually:",
268
- # list(SUPPORTED_LANGUAGES.keys()),
269
- # format_func=lambda x: SUPPORTED_LANGUAGES[x],
270
- # index=0
271
- # )
272
 
273
  # Load the selected emotion classifier
274
  emotion_classifier = load_emotion_classifier(selected_model_key)
@@ -301,76 +344,78 @@ def main():
301
  )
302
 
303
  if user_input:
304
- # Language Detection
305
- if auto_detect:
306
- detected_language = detect_language(user_input)
307
- #else:
308
- # detected_language = manual_language
309
-
310
- # Display language detection results
311
- display_language_info(detected_language)
312
-
313
- # Emotion Detection
314
- with st.spinner("Analyzing emotions..."):
315
- emotion_predictions = emotion_classifier(user_input)
316
-
317
- # Display top predictions in sidebar
318
- display_top_predictions(emotion_predictions, selected_language, num_predictions)
319
-
320
- # Display Emotions in main area (top 5)
321
- st.subheader(LANGUAGES[selected_language]['emotions_header'])
322
- top_5_emotions = sorted(emotion_predictions, key=lambda x: x['score'], reverse=True)[:5]
323
-
324
- # Create columns for better display
325
- col1, col2 = st.columns(2)
326
-
327
- for i, prediction in enumerate(top_5_emotions):
328
- emotion = prediction['label']
329
- score = prediction['score']
330
- percentage = score * 100
331
 
332
- # Add emotion category indicator
333
- emotion_category = categorize_emotion(emotion)
334
- category_emoji = "😊" if emotion_category == "positive" else "πŸ˜”" if emotion_category == "negative" else "😐"
335
 
336
- if i % 2 == 0:
337
- with col1:
338
- st.metric(
339
- label=f"{category_emoji} {emotion.title()}",
340
- value=f"{percentage:.1f}%",
341
- delta=None
342
- )
343
- else:
344
- with col2:
345
- st.metric(
346
- label=f"{category_emoji} {emotion.title()}",
347
- value=f"{percentage:.1f}%",
348
- delta=None
349
- )
350
-
351
- # Get AI Response with enhanced emotional intelligence
352
- with st.spinner("Generating emotionally intelligent response..."):
353
- ai_response = get_ai_response(user_input, emotion_predictions, detected_language)
354
-
355
- # Display AI Response
356
- st.subheader(f"πŸ€– {LANGUAGES[selected_language]['response_header']}")
357
-
358
- # Show dominant emotion and response language
359
- dominant_emotion = max(emotion_predictions, key=lambda x: x['score'])
360
- language_name = get_language_name(detected_language)
361
-
362
- #st.markdown(f"**Responding with:** {dominant_emotion['label'].title()} emotion in {language_name}")
363
- #st.markdown("---")
364
-
365
- # Display the response in a nice container
366
- with st.container():
367
- #st.markdown(f"**πŸ€– AI Response:**")
368
- st.write(ai_response)
369
-
370
- # Add emotion intensity indicator
371
- emotion_score = dominant_emotion['score']
372
- intensity = "High" if emotion_score > 0.7 else "Moderate" if emotion_score > 0.4 else "Low"
373
- st.caption(f"Emotion Intensity: {intensity} ({emotion_score:.2f})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
 
375
  # Run the main function
376
  if __name__ == "__main__":
 
54
  'tr': 'Turkish'
55
  }
56
 
57
+ def normalize_emotion_predictions(predictions):
58
+ """
59
+ Normalize emotion predictions to ensure consistent format.
60
+ Handles different return formats from Hugging Face pipelines.
61
+ """
62
+ try:
63
+ # If predictions is a list of lists (multiple inputs)
64
+ if isinstance(predictions, list) and len(predictions) > 0:
65
+ if isinstance(predictions[0], list):
66
+ # Take the first prediction set
67
+ predictions = predictions[0]
68
+
69
+ # Ensure each prediction has the required keys
70
+ normalized = []
71
+ for pred in predictions:
72
+ if isinstance(pred, dict):
73
+ # Handle different possible key names
74
+ label = pred.get('label') or pred.get('LABEL') or pred.get('emotion', 'unknown')
75
+ score = pred.get('score') or pred.get('SCORE') or pred.get('confidence', 0.0)
76
+
77
+ normalized.append({
78
+ 'label': str(label).lower(),
79
+ 'score': float(score)
80
+ })
81
+ else:
82
+ # Handle unexpected format
83
+ st.warning(f"Unexpected prediction format: {pred}")
84
+ continue
85
+
86
+ return normalized if normalized else [{'label': 'neutral', 'score': 1.0}]
87
+
88
+ else:
89
+ # Handle case where predictions is not in expected format
90
+ st.warning(f"Unexpected predictions format: {type(predictions)}")
91
+ return [{'label': 'neutral', 'score': 1.0}]
92
+
93
+ except Exception as e:
94
+ st.error(f"Error normalizing predictions: {str(e)}")
95
+ return [{'label': 'neutral', 'score': 1.0}]
96
 
97
  def detect_language(text):
98
  """Detect the language of the input text."""
 
203
  try:
204
  # Use the HF token if available for authentication
205
  if hf_token:
206
+ return pipeline("text-classification", model=model_name, use_auth_token=hf_token, top_k=None)
207
  else:
208
+ return pipeline("text-classification", model=model_name, top_k=None)
209
  except Exception as e:
210
  st.error(f"Error loading model {model_name}: {str(e)}")
211
  return None
212
 
213
  def get_ai_response(user_input, emotion_predictions, detected_language):
214
  """Generates AI response based on user input, detected emotions, and language."""
215
+ try:
216
+ # Ensure predictions are normalized
217
+ normalized_predictions = normalize_emotion_predictions(emotion_predictions)
218
+
219
+ dominant_emotion = None
220
+ max_score = 0
221
+
222
+ for prediction in normalized_predictions:
223
+ if prediction['score'] > max_score:
224
+ max_score = prediction['score']
225
+ dominant_emotion = prediction['label']
226
+
227
+ if dominant_emotion is None:
228
+ return "Error: No emotion detected for response generation."
229
+
230
+ # Create enhanced prompt with language and emotion context
231
+ prompt_text = create_enhanced_prompt(dominant_emotion, user_input, detected_language, max_score)
232
+ response = generate_text(prompt_text)
233
+
234
+ return response
235
 
236
+ except Exception as e:
237
+ st.error(f"Error generating AI response: {str(e)}")
238
+ return "I'm sorry, I encountered an error while generating a response."
239
 
240
  def display_top_predictions(emotion_predictions, selected_language, num_predictions=3):
241
  """Display top emotion predictions in sidebar."""
242
+ try:
243
+ # Normalize predictions first
244
+ normalized_predictions = normalize_emotion_predictions(emotion_predictions)
245
+
246
+ # Sort predictions by score in descending order
247
+ sorted_predictions = sorted(normalized_predictions, key=lambda x: x['score'], reverse=True)
248
+
249
+ # Take top N predictions
250
+ top_predictions = sorted_predictions[:num_predictions]
 
 
 
 
 
251
 
252
+ # Display in sidebar
 
 
 
253
  st.sidebar.markdown("---")
254
+ st.sidebar.subheader("🎯 Top Emotion Predictions")
255
+
256
+ for i, prediction in enumerate(top_predictions, 1):
257
+ emotion = prediction['label']
258
+ score = prediction['score']
259
+ percentage = score * 100
260
+
261
+ # Create a progress bar for visual representation
262
+ st.sidebar.markdown(f"**{i}. {emotion.title()}**")
263
+ st.sidebar.progress(score)
264
+ st.sidebar.markdown(f"Score: {percentage:.1f}%")
265
+ st.sidebar.markdown("---")
266
+
267
+ except Exception as e:
268
+ st.sidebar.error(f"Error displaying predictions: {str(e)}")
269
 
270
  def display_language_info(detected_language, confidence_scores=None):
271
  """Display detected language information."""
 
311
  )
312
 
313
  # Language detection settings
314
+ auto_detect = True
 
 
 
 
 
 
 
 
 
 
315
 
316
  # Load the selected emotion classifier
317
  emotion_classifier = load_emotion_classifier(selected_model_key)
 
344
  )
345
 
346
  if user_input:
347
+ try:
348
+ # Language Detection
349
+ if auto_detect:
350
+ detected_language = detect_language(user_input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
 
352
+ # Display language detection results
353
+ display_language_info(detected_language)
 
354
 
355
+ # Emotion Detection
356
+ with st.spinner("Analyzing emotions..."):
357
+ emotion_predictions = emotion_classifier(user_input)
358
+
359
+ # Normalize predictions
360
+ normalized_predictions = normalize_emotion_predictions(emotion_predictions)
361
+
362
+ # Display top predictions in sidebar
363
+ display_top_predictions(emotion_predictions, selected_language, num_predictions)
364
+
365
+ # Display Emotions in main area (top 5)
366
+ st.subheader(LANGUAGES[selected_language]['emotions_header'])
367
+ top_5_emotions = sorted(normalized_predictions, key=lambda x: x['score'], reverse=True)[:5]
368
+
369
+ # Create columns for better display
370
+ col1, col2 = st.columns(2)
371
+
372
+ for i, prediction in enumerate(top_5_emotions):
373
+ emotion = prediction['label']
374
+ score = prediction['score']
375
+ percentage = score * 100
376
+
377
+ # Add emotion category indicator
378
+ emotion_category = categorize_emotion(emotion)
379
+ category_emoji = "😊" if emotion_category == "positive" else "πŸ˜”" if emotion_category == "negative" else "😐"
380
+
381
+ if i % 2 == 0:
382
+ with col1:
383
+ st.metric(
384
+ label=f"{category_emoji} {emotion.title()}",
385
+ value=f"{percentage:.1f}%",
386
+ delta=None
387
+ )
388
+ else:
389
+ with col2:
390
+ st.metric(
391
+ label=f"{category_emoji} {emotion.title()}",
392
+ value=f"{percentage:.1f}%",
393
+ delta=None
394
+ )
395
+
396
+ # Get AI Response with enhanced emotional intelligence
397
+ with st.spinner("Generating emotionally intelligent response..."):
398
+ ai_response = get_ai_response(user_input, emotion_predictions, detected_language)
399
+
400
+ # Display AI Response
401
+ st.subheader(f"πŸ€– {LANGUAGES[selected_language]['response_header']}")
402
+
403
+ # Show dominant emotion and response language
404
+ dominant_emotion = max(normalized_predictions, key=lambda x: x['score'])
405
+ language_name = get_language_name(detected_language)
406
+
407
+ # Display the response in a nice container
408
+ with st.container():
409
+ st.write(ai_response)
410
+
411
+ # Add emotion intensity indicator
412
+ emotion_score = dominant_emotion['score']
413
+ intensity = "High" if emotion_score > 0.7 else "Moderate" if emotion_score > 0.4 else "Low"
414
+ st.caption(f"Emotion Intensity: {intensity} ({emotion_score:.2f})")
415
+
416
+ except Exception as e:
417
+ st.error(f"An error occurred: {str(e)}")
418
+ st.error("Please try again with different input or check your configuration.")
419
 
420
  # Run the main function
421
  if __name__ == "__main__":