Spaces:
Running
Running
Update app.py
Browse files
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 #
|
12 |
|
13 |
-
#
|
14 |
EMOTION_MAPPING = {
|
15 |
-
"
|
16 |
-
"underlying": ["
|
17 |
-
"recommendation": "
|
18 |
-
"polarity": 1
|
|
|
19 |
},
|
20 |
-
"
|
21 |
-
"underlying": ["
|
22 |
-
"recommendation": "
|
23 |
-
"polarity": -1
|
|
|
24 |
},
|
25 |
-
"
|
26 |
-
"underlying": ["
|
27 |
-
"recommendation": "
|
28 |
-
"polarity":
|
|
|
29 |
},
|
30 |
"fear": {
|
31 |
-
"underlying": ["
|
32 |
-
"recommendation": "
|
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 |
-
"
|
46 |
-
"underlying": ["
|
47 |
-
"recommendation": "
|
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
|
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
|
83 |
-
|
84 |
text_lower = text.lower()
|
85 |
|
86 |
-
for
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
return
|
94 |
|
95 |
def analyze_text(text):
|
96 |
-
# Detect
|
97 |
-
|
98 |
|
99 |
-
#
|
100 |
emo_results = emotion_pipeline(text, top_k=None)
|
101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
-
#
|
104 |
-
for emo, score in
|
105 |
-
if
|
106 |
-
|
|
|
|
|
|
|
|
|
107 |
|
108 |
# Generate detailed analysis
|
109 |
details = ""
|
110 |
positive_emotions = []
|
111 |
negative_emotions = []
|
112 |
|
113 |
-
for i, (emo, score) in enumerate(
|
114 |
emotion_data = EMOTION_MAPPING.get(emo, {
|
115 |
-
"underlying": ["
|
116 |
-
"recommendation": "This emotion
|
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
|
132 |
conclusion = "\n=== Final Analysis ===\n"
|
133 |
|
134 |
if positive_emotions:
|
135 |
-
conclusion += f"Positive emotions
|
136 |
if negative_emotions:
|
137 |
-
conclusion += f"Negative emotions
|
138 |
|
139 |
-
#
|
140 |
-
if positive_emotions and
|
141 |
-
final_rec = "
|
|
|
|
|
142 |
elif negative_emotions and not positive_emotions:
|
143 |
-
final_rec = "Consider
|
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 = "
|
151 |
|
152 |
conclusion += f"\nFinal Recommendation: {final_rec}"
|
153 |
|
154 |
-
visualization = create_visualization(
|
155 |
return details + conclusion, visualization
|
156 |
|
157 |
iface = gr.Interface(
|
158 |
fn=analyze_text,
|
159 |
-
inputs=gr.Textbox(label="Your Text", placeholder="
|
160 |
outputs=[
|
161 |
-
gr.Textbox(label="
|
162 |
-
gr.HTML(label="
|
163 |
],
|
164 |
-
title="
|
165 |
-
description="
|
166 |
examples=[
|
167 |
-
["I'm thrilled about my promotion but anxious about the
|
168 |
-
["
|
169 |
-
["
|
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 |
|