NaimaAqeel commited on
Commit
b0bda03
·
verified ·
1 Parent(s): 0215a29

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -95
app.py CHANGED
@@ -6,53 +6,59 @@ import base64
6
 
7
  # Load models
8
  emotion_pipeline = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion")
9
- toxicity_pipeline = pipeline("text-classification", model="martin-ha/toxic-comment-model")
10
 
11
- EMO_THRESHOLD = 0.05 # Minimum confidence threshold for emotions
12
-
13
- # Comprehensive emotion mapping
14
  EMOTION_MAPPING = {
15
- "excitement": {
16
- "underlying": ["Anticipation", "Eagerness", "Enthusiasm"],
17
- "recommendation": "Channel this energy into planning and goal-setting!",
18
  "polarity": 1,
19
- "keywords": ["thrilled", "excited", "pumped"]
 
 
 
 
 
 
20
  },
21
  "anxiety": {
22
  "underlying": ["Worry", "Unease", "Apprehension", "Nervousness"],
23
  "recommendation": "Try box breathing (4-4-4-4) and focus on preparation.",
24
  "polarity": -1,
25
- "keywords": ["anxious", "nervous", "apprehensive"]
26
- },
27
- "joy": {
28
- "underlying": ["Contentment", "Pleasure", "Delight"],
29
- "recommendation": "Savor this moment and share your happiness!",
30
- "polarity": 1,
31
- "keywords": ["happy", "joyful"]
32
  },
33
  "fear": {
34
- "underlying": ["Dread", "Panic", "Terror"],
35
- "recommendation": "Practice grounding techniques and focus on the present.",
36
  "polarity": -1,
37
- "keywords": ["scared", "afraid"]
38
- },
39
- "pride": {
40
- "underlying": ["Accomplishment", "Self-worth", "Achievement"],
41
- "recommendation": "Celebrate your success while staying humble.",
42
- "polarity": 1,
43
- "keywords": ["proud", "accomplished"]
44
  },
45
- "disappointment": {
46
- "underlying": ["Letdown", "Frustration", "Regret"],
47
- "recommendation": "Acknowledge the feeling, then focus on what you can control.",
48
  "polarity": -1,
49
- "keywords": ["disappointed", "let down"]
 
 
 
 
 
 
50
  }
51
  }
52
 
53
  def create_visualization(emotions):
54
  fig, ax = plt.subplots(figsize=(8,5))
55
- colors = ['#4CAF50' if EMOTION_MAPPING[e]['polarity'] > 0 else '#F44336' for e in emotions.keys()]
 
 
 
 
 
 
 
 
56
  ax.barh(list(emotions.keys()), list(emotions.values()), color=colors)
57
  ax.set_xlim(0,1)
58
  ax.set_xlabel("Confidence Score")
@@ -65,104 +71,88 @@ def create_visualization(emotions):
65
  plt.close()
66
  return f'<img src="data:image/png;base64,{base64.b64encode(buf.read()).decode("utf-8")}">'
67
 
68
- def detect_keyword_emotions(text):
 
69
  emotions = {}
70
  text_lower = text.lower()
71
 
72
  for emo, data in EMOTION_MAPPING.items():
73
  for keyword in data['keywords']:
74
  if keyword in text_lower:
75
- # Use higher confidence for exact matches
76
- confidence = 0.9 if keyword in text_lower.split() else 0.7
77
  if confidence > emotions.get(emo, 0):
78
  emotions[emo] = confidence
79
- return emotions
80
-
81
- def analyze_text(text):
82
- # Detect keyword-based emotions first
83
- keyword_emotions = detect_keyword_emotions(text)
84
 
85
- # Get base model emotions
86
  emo_results = emotion_pipeline(text, top_k=None)
87
- base_emotions = {e["label"].lower(): e["score"] for e in emo_results
88
- if e["score"] > EMO_THRESHOLD}
89
-
90
- # Merge emotions with keyword emotions taking priority
91
- final_emotions = {}
92
-
93
- # Add keyword emotions first
94
- for emo, score in keyword_emotions.items():
95
- final_emotions[emo] = score
96
 
97
- # Add base emotions only if not already detected by keywords
98
- for emo, score in base_emotions.items():
99
- # Skip if we already have a more specific version of this emotion
100
- if (emo == 'joy' and 'excitement' in final_emotions) or \
101
- (emo == 'fear' and 'anxiety' in final_emotions):
102
- continue
103
- if emo not in final_emotions:
104
- final_emotions[emo] = score
105
 
106
- # Generate detailed analysis
107
  details = ""
108
- positive_emotions = []
109
- negative_emotions = []
110
 
111
- for i, (emo, score) in enumerate(final_emotions.items(), 1):
112
- emotion_data = EMOTION_MAPPING.get(emo, {
113
- "underlying": ["Complex feeling"],
114
- "recommendation": "This emotion warrants careful reflection.",
115
  "polarity": 0
116
  })
117
 
118
- polarity = "Positive" if emotion_data["polarity"] > 0 else "Negative" if emotion_data["polarity"] < 0 else "Neutral"
119
 
120
- details += f"Emotion {i}: {emo.capitalize()} ({polarity}, Confidence: {score:.2f})\n"
121
- details += f"Underlying: {', '.join(emotion_data['underlying'])}\n"
122
- details += f"Recommendation: {emotion_data['recommendation']}\n\n"
123
 
124
- if emotion_data["polarity"] > 0:
125
- positive_emotions.append(emo)
126
- elif emotion_data["polarity"] < 0:
127
- negative_emotions.append(emo)
128
 
129
- # Generate final analysis
130
  conclusion = "\n=== Final Analysis ===\n"
 
 
131
 
132
- if positive_emotions:
133
- conclusion += f"Positive emotions: {', '.join(positive_emotions)}\n"
134
- if negative_emotions:
135
- conclusion += f"Negative emotions: {', '.join(negative_emotions)}\n"
136
-
137
- # Context-aware final recommendation
138
- if "excitement" in positive_emotions and "anxiety" in negative_emotions:
139
- final_rec = "This exciting transition naturally brings some nerves. Make an action plan to build confidence."
140
- elif positive_emotions and not negative_emotions:
141
- final_rec = "Fully enjoy these positive feelings!"
142
- elif negative_emotions and not positive_emotions:
143
- final_rec = "Consider discussing these feelings with someone you trust."
144
  else:
145
- final_rec = "Reflect on these mixed emotions to understand yourself better."
146
 
147
  conclusion += f"\nFinal Recommendation: {final_rec}"
148
 
149
- visualization = create_visualization(final_emotions)
150
- return details + conclusion, visualization
151
 
152
  iface = gr.Interface(
153
  fn=analyze_text,
154
- inputs=gr.Textbox(label="Your Text", placeholder="Describe your feelings..."),
155
  outputs=[
156
- gr.Textbox(label="Emotion Analysis"),
157
- gr.HTML(label="Visualization")
158
  ],
159
- title="Precision Emotion Analyzer",
160
- description="Accurately detects specific emotions without duplicates, providing tailored recommendations.",
161
  examples=[
162
- ["I'm thrilled about my promotion but anxious about the responsibilities"],
163
- ["Feeling proud of my accomplishment yet disappointed with the recognition"],
164
- ["I'm excited and nervous about the first day at my new job"]
165
- ]
 
 
 
166
  )
167
 
168
  iface.launch()
 
6
 
7
  # Load models
8
  emotion_pipeline = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion")
9
+ EMO_THRESHOLD = 0.1 # Increased threshold for more confident detections
10
 
11
+ # Enhanced emotion mapping with common expressions
 
 
12
  EMOTION_MAPPING = {
13
+ "joy": {
14
+ "underlying": ["Contentment", "Pleasure", "Delight", "Happiness"],
15
+ "recommendation": "Savor this positive feeling!",
16
  "polarity": 1,
17
+ "keywords": ["happy", "joy", "glad", "delighted"]
18
+ },
19
+ "sadness": {
20
+ "underlying": ["Grief", "Loneliness", "Sorrow", "Melancholy"],
21
+ "recommendation": "It's okay to feel this way. Consider talking to someone.",
22
+ "polarity": -1,
23
+ "keywords": ["sad", "unhappy", "depressed", "miserable"]
24
  },
25
  "anxiety": {
26
  "underlying": ["Worry", "Unease", "Apprehension", "Nervousness"],
27
  "recommendation": "Try box breathing (4-4-4-4) and focus on preparation.",
28
  "polarity": -1,
29
+ "keywords": ["anxious", "nervous", "worried", "stressed"]
 
 
 
 
 
 
30
  },
31
  "fear": {
32
+ "underlying": ["Dread", "Panic", "Terror", "Fright"],
33
+ "recommendation": "Practice grounding techniques to stay present.",
34
  "polarity": -1,
35
+ "keywords": ["scared", "afraid", "fearful"]
 
 
 
 
 
 
36
  },
37
+ "anger": {
38
+ "underlying": ["Frustration", "Irritation", "Rage", "Resentment"],
39
+ "recommendation": "Take deep breaths before responding.",
40
  "polarity": -1,
41
+ "keywords": ["angry", "mad", "furious"]
42
+ },
43
+ "focus": {
44
+ "underlying": ["Concentration", "Attention", "Engagement"],
45
+ "recommendation": "Maintain this productive state with regular breaks.",
46
+ "polarity": 1,
47
+ "keywords": ["focused", "concentrating", "studying"]
48
  }
49
  }
50
 
51
  def create_visualization(emotions):
52
  fig, ax = plt.subplots(figsize=(8,5))
53
+ colors = []
54
+ for e in emotions.keys():
55
+ if e in EMOTION_MAPPING:
56
+ polarity = EMOTION_MAPPING[e]['polarity']
57
+ color = '#4CAF50' if polarity > 0 else '#F44336'
58
+ else:
59
+ color = '#9E9E9E' # Neutral for unknown
60
+ colors.append(color)
61
+
62
  ax.barh(list(emotions.keys()), list(emotions.values()), color=colors)
63
  ax.set_xlim(0,1)
64
  ax.set_xlabel("Confidence Score")
 
71
  plt.close()
72
  return f'<img src="data:image/png;base64,{base64.b64encode(buf.read()).decode("utf-8")}">'
73
 
74
+ def detect_emotions(text):
75
+ # Keyword detection first
76
  emotions = {}
77
  text_lower = text.lower()
78
 
79
  for emo, data in EMOTION_MAPPING.items():
80
  for keyword in data['keywords']:
81
  if keyword in text_lower:
82
+ confidence = 0.9 if any(kw == keyword for kw in text_lower.split()) else 0.7
 
83
  if confidence > emotions.get(emo, 0):
84
  emotions[emo] = confidence
 
 
 
 
 
85
 
86
+ # Model detection for remaining
87
  emo_results = emotion_pipeline(text, top_k=None)
88
+ for e in emo_results:
89
+ if e["score"] > EMO_THRESHOLD and e["label"].lower() not in emotions:
90
+ emotions[e["label"].lower()] = e["score"]
 
 
 
 
 
 
91
 
92
+ return emotions
93
+
94
+ def analyze_text(text):
95
+ emotions = detect_emotions(text)
 
 
 
 
96
 
 
97
  details = ""
98
+ positive = []
99
+ negative = []
100
 
101
+ for i, (emo, score) in enumerate(emotions.items(), 1):
102
+ data = EMOTION_MAPPING.get(emo, {
103
+ "underlying": ["Complex emotion"],
104
+ "recommendation": "This feeling deserves reflection.",
105
  "polarity": 0
106
  })
107
 
108
+ pol = "Positive" if data["polarity"] > 0 else "Negative" if data["polarity"] < 0 else "Neutral"
109
 
110
+ details += f"Emotion {i}: {emo.capitalize()} ({pol}, Confidence: {score:.2f})\n"
111
+ details += f"Underlying: {', '.join(data['underlying'])}\n"
112
+ details += f"Recommendation: {data['recommendation']}\n\n"
113
 
114
+ if data["polarity"] > 0: positive.append(emo)
115
+ elif data["polarity"] < 0: negative.append(emo)
 
 
116
 
 
117
  conclusion = "\n=== Final Analysis ===\n"
118
+ if positive: conclusion += f"Positive emotions: {', '.join(positive)}\n"
119
+ if negative: conclusion += f"Negative emotions: {', '.join(negative)}\n"
120
 
121
+ # Enhanced recommendation logic
122
+ if "focus" in positive and not negative:
123
+ final_rec = "Great focus! Maintain this productive state."
124
+ elif positive and negative:
125
+ if "anxiety" in negative:
126
+ final_rec = "Channel your anxiety into constructive planning."
127
+ else:
128
+ final_rec = "Balance these mixed emotions with mindful reflection."
129
+ elif positive:
130
+ final_rec = "Enjoy these positive feelings!"
131
+ elif negative:
132
+ final_rec = "Consider discussing these feelings with someone."
133
  else:
134
+ final_rec = "The emotional tone is neutral."
135
 
136
  conclusion += f"\nFinal Recommendation: {final_rec}"
137
 
138
+ viz = create_visualization(emotions)
139
+ return details + conclusion, viz
140
 
141
  iface = gr.Interface(
142
  fn=analyze_text,
143
+ inputs=gr.Textbox(label="How are you feeling?", placeholder="I feel..."),
144
  outputs=[
145
+ gr.Textbox(label="Emotion Breakdown"),
146
+ gr.HTML(label="Emotion Intensity")
147
  ],
 
 
148
  examples=[
149
+ ["I am happy but at the same time anxious"],
150
+ ["I'm focused on studying but afraid of failure"],
151
+ ["I feel sad and lonely today"],
152
+ ["I'm angry about what happened"]
153
+ ],
154
+ title="Advanced Emotion Analyzer",
155
+ description="Accurately detects emotions in both simple and complex sentences."
156
  )
157
 
158
  iface.launch()