Spaces:
Running
Running
Update app.py
Browse files
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 |
-
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
# Comprehensive emotion mapping
|
14 |
EMOTION_MAPPING = {
|
15 |
-
"
|
16 |
-
"underlying": ["
|
17 |
-
"recommendation": "
|
18 |
"polarity": 1,
|
19 |
-
"keywords": ["
|
|
|
|
|
|
|
|
|
|
|
|
|
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", "
|
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
|
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 |
-
"
|
46 |
-
"underlying": ["
|
47 |
-
"recommendation": "
|
48 |
"polarity": -1,
|
49 |
-
"keywords": ["
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
}
|
51 |
}
|
52 |
|
53 |
def create_visualization(emotions):
|
54 |
fig, ax = plt.subplots(figsize=(8,5))
|
55 |
-
colors = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
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 |
-
|
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 |
-
#
|
86 |
emo_results = emotion_pipeline(text, top_k=None)
|
87 |
-
|
88 |
-
|
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 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
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 |
-
|
109 |
-
|
110 |
|
111 |
-
for i, (emo, score) in enumerate(
|
112 |
-
|
113 |
-
"underlying": ["Complex
|
114 |
-
"recommendation": "This
|
115 |
"polarity": 0
|
116 |
})
|
117 |
|
118 |
-
|
119 |
|
120 |
-
details += f"Emotion {i}: {emo.capitalize()} ({
|
121 |
-
details += f"Underlying: {', '.join(
|
122 |
-
details += f"Recommendation: {
|
123 |
|
124 |
-
if
|
125 |
-
|
126 |
-
elif emotion_data["polarity"] < 0:
|
127 |
-
negative_emotions.append(emo)
|
128 |
|
129 |
-
# Generate final analysis
|
130 |
conclusion = "\n=== Final Analysis ===\n"
|
|
|
|
|
131 |
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
elif
|
141 |
-
final_rec = "
|
142 |
-
elif
|
143 |
-
final_rec = "Consider discussing these feelings with someone
|
144 |
else:
|
145 |
-
final_rec = "
|
146 |
|
147 |
conclusion += f"\nFinal Recommendation: {final_rec}"
|
148 |
|
149 |
-
|
150 |
-
return details + conclusion,
|
151 |
|
152 |
iface = gr.Interface(
|
153 |
fn=analyze_text,
|
154 |
-
inputs=gr.Textbox(label="
|
155 |
outputs=[
|
156 |
-
gr.Textbox(label="Emotion
|
157 |
-
gr.HTML(label="
|
158 |
],
|
159 |
-
title="Precision Emotion Analyzer",
|
160 |
-
description="Accurately detects specific emotions without duplicates, providing tailored recommendations.",
|
161 |
examples=[
|
162 |
-
["I
|
163 |
-
["
|
164 |
-
["I
|
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()
|