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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -86
app.py CHANGED
@@ -8,65 +8,51 @@ import base64
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 # include even lower confidence emotions
12
 
13
- # Expanded emotion mapping with special cases
14
  EMOTION_MAPPING = {
15
- "joy": {
16
- "underlying": ["Relief", "Contentment", "Pride", "Love", "Gratitude", "Hope"],
17
- "recommendation": "Keep enjoying and share your happiness with others!",
18
- "polarity": 1
 
19
  },
20
- "sadness": {
21
- "underlying": ["Loneliness", "Grief", "Disappointment", "Shame", "Helplessness", "Regret"],
22
- "recommendation": "Consider talking to someone or journaling about your feelings.",
23
- "polarity": -1
 
24
  },
25
- "anger": {
26
- "underlying": ["Frustration", "Injustice", "Betrayal", "Resentment"],
27
- "recommendation": "Try deep breathing or physical activity to release tension.",
28
- "polarity": -1
 
29
  },
30
  "fear": {
31
- "underlying": ["Anxiety", "Insecurity", "Dread", "Worry"],
32
- "recommendation": "Focus on what you can control and practice grounding techniques.",
33
- "polarity": -1
34
- },
35
- "disappointment": {
36
- "underlying": ["Letdown", "Unmet expectations", "Discouragement"],
37
- "recommendation": "Acknowledge the feeling, then refocus on what you can influence.",
38
- "polarity": -1
39
  },
40
  "pride": {
41
  "underlying": ["Accomplishment", "Self-worth", "Achievement"],
42
  "recommendation": "Celebrate your success while staying humble.",
43
- "polarity": 1
 
44
  },
45
- "anxiety": {
46
- "underlying": ["Worry", "Unease", "Apprehension", "Nervousness"],
47
- "recommendation": "Try box breathing (4-4-4-4) and focus on preparation.",
48
- "polarity": -1
49
- },
50
- "excitement": {
51
- "underlying": ["Anticipation", "Eagerness", "Enthusiasm"],
52
- "recommendation": "Channel this energy into planning and goal-setting!",
53
- "polarity": 1
54
  }
55
  }
56
 
57
- # Special emotion triggers
58
- SPECIAL_EMOTION_TRIGGERS = {
59
- "anxious": {"emotion": "anxiety", "confidence": 0.8},
60
- "thrilled": {"emotion": "excitement", "confidence": 0.9},
61
- "devastated": {"emotion": "grief", "confidence": 0.85},
62
- "overjoyed": {"emotion": "elation", "confidence": 0.95},
63
- "apprehensive": {"emotion": "wariness", "confidence": 0.75}
64
- }
65
-
66
  def create_visualization(emotions):
67
  fig, ax = plt.subplots(figsize=(8,5))
68
- colors = ['#4CAF50' if EMOTION_MAPPING.get(e, {}).get('polarity', 0) > 0
69
- else '#F44336' for e in emotions.keys()]
70
  ax.barh(list(emotions.keys()), list(emotions.values()), color=colors)
71
  ax.set_xlim(0,1)
72
  ax.set_xlabel("Confidence Score")
@@ -79,41 +65,53 @@ def create_visualization(emotions):
79
  plt.close()
80
  return f'<img src="data:image/png;base64,{base64.b64encode(buf.read()).decode("utf-8")}">'
81
 
82
- def detect_special_emotions(text):
83
- special_emotions = {}
84
  text_lower = text.lower()
85
 
86
- for trigger, data in SPECIAL_EMOTION_TRIGGERS.items():
87
- if trigger in text_lower:
88
- emotion = data["emotion"]
89
- # Only add if not already detected or if our confidence is higher
90
- if data["confidence"] > special_emotions.get(emotion, 0):
91
- special_emotions[emotion] = data["confidence"]
92
-
93
- return special_emotions
94
 
95
  def analyze_text(text):
96
- # Detect special cases first
97
- special_emotions = detect_special_emotions(text)
98
 
99
- # Original emotion detection
100
  emo_results = emotion_pipeline(text, top_k=None)
101
- emotions = {e["label"].lower(): e["score"] for e in emo_results if e["score"] > EMO_THRESHOLD}
 
 
 
 
 
 
 
 
102
 
103
- # Merge with special cases (keeping higher confidence)
104
- for emo, score in special_emotions.items():
105
- if score > emotions.get(emo, 0):
106
- emotions[emo] = score
 
 
 
 
107
 
108
  # Generate detailed analysis
109
  details = ""
110
  positive_emotions = []
111
  negative_emotions = []
112
 
113
- for i, (emo, score) in enumerate(emotions.items(), 1):
114
  emotion_data = EMOTION_MAPPING.get(emo, {
115
- "underlying": ["Unknown"],
116
- "recommendation": "This emotion is complex. Reflect on its source.",
117
  "polarity": 0
118
  })
119
 
@@ -128,45 +126,42 @@ def analyze_text(text):
128
  elif emotion_data["polarity"] < 0:
129
  negative_emotions.append(emo)
130
 
131
- # Generate balanced conclusion
132
  conclusion = "\n=== Final Analysis ===\n"
133
 
134
  if positive_emotions:
135
- conclusion += f"Positive emotions detected: {', '.join(positive_emotions)}\n"
136
  if negative_emotions:
137
- conclusion += f"Negative emotions detected: {', '.join(negative_emotions)}\n"
138
 
139
- # Final recommendation blending
140
- if positive_emotions and not negative_emotions:
141
- final_rec = "Enjoy this positive moment fully!"
 
 
142
  elif negative_emotions and not positive_emotions:
143
- final_rec = "Consider reaching out for support if these feelings persist."
144
- elif positive_emotions and negative_emotions:
145
- if "anxiety" in negative_emotions and "excitement" in positive_emotions:
146
- final_rec = "This exciting change comes with natural nerves. Make lists of what you can control to ease anxiety."
147
- else:
148
- final_rec = "You're experiencing mixed emotions. Acknowledge both sides - celebrate the positive while addressing the negative."
149
  else:
150
- final_rec = "The emotional tone is neutral or complex."
151
 
152
  conclusion += f"\nFinal Recommendation: {final_rec}"
153
 
154
- visualization = create_visualization(emotions)
155
  return details + conclusion, visualization
156
 
157
  iface = gr.Interface(
158
  fn=analyze_text,
159
- inputs=gr.Textbox(label="Your Text", placeholder="I feel proud but also disappointed..."),
160
  outputs=[
161
- gr.Textbox(label="Detailed Analysis"),
162
- gr.HTML(label="Emotion Visualization")
163
  ],
164
- title="Advanced Emotion Analyzer",
165
- description="Detects complex emotional states including underlying emotions and provides balanced recommendations.",
166
  examples=[
167
- ["I'm thrilled about my promotion but anxious about the increased responsibilities"],
168
- ["I feel overjoyed yet apprehensive about the future"],
169
- ["This situation makes me both hopeful and devastated"]
170
  ]
171
  )
172
 
 
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
  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
 
 
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