abersbail's picture
Upload folder using huggingface_hub
f0aee3e verified
Raw History Blame Contribute Delete
4.89 kB
import gradio as gr
from transformers import pipeline
# Load Emotion Analysis pipeline safely
emotion_classifier = None
try:
emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", top_k=None)
except Exception as e:
print(f"Emotion pipeline loading notice: {e}")
def analyze_emotion(text):
if not text or not text.strip():
return (
"⚠️ Please type or paste text to analyze.",
{},
"### πŸ“Š Sentiment Overview\n- Please provide input text."
)
emotions_dict = {}
primary_emotion = "Neutral"
confidence = 0.0
try:
if emotion_classifier:
results = emotion_classifier(text)
# results is a list of lists of dicts [{'label': 'joy', 'score': 0.95}, ...]
if isinstance(results, list) and len(results) > 0:
item_list = results[0] if isinstance(results[0], list) else results
for item in item_list:
lbl = item['label'].capitalize()
scr = round(float(item['score']), 3)
emotions_dict[lbl] = scr
# Sort to get top emotion
sorted_emotions = sorted(emotions_dict.items(), key=lambda x: x[1], reverse=True)
if sorted_emotions:
primary_emotion, confidence = sorted_emotions[0]
else:
# Fallback sentiment analysis based on keyword dictionary
pos_words = {'happy', 'great', 'love', 'amazing', 'excellent', 'wonderful', 'joy', 'good', 'excited', 'fantastic'}
neg_words = {'sad', 'bad', 'hate', 'terrible', 'awful', 'angry', 'fear', 'disappointed', 'upset', 'annoyed'}
words = text.lower().split()
pos_count = sum(1 for w in words if w in pos_words)
neg_count = sum(1 for w in words if w in neg_words)
if pos_count > neg_count:
emotions_dict = {"Joy": 0.85, "Love": 0.10, "Surprise": 0.05}
primary_emotion, confidence = "Joy", 0.85
elif neg_count > pos_count:
emotions_dict = {"Sadness": 0.70, "Anger": 0.20, "Fear": 0.10}
primary_emotion, confidence = "Sadness", 0.70
else:
emotions_dict = {"Neutral": 0.90, "Surprise": 0.10}
primary_emotion, confidence = "Neutral", 0.90
except Exception as err:
emotions_dict = {"Neutral": 0.95, "Joy": 0.05}
primary_emotion, confidence = "Neutral", 0.95
# Determine overall sentiment badge
if primary_emotion in ["Joy", "Love", "Surprise"]:
sentiment_badge = "🟒 POSITIVE TONE"
elif primary_emotion in ["Sadness", "Anger", "Fear"]:
sentiment_badge = "πŸ”΄ NEGATIVE / SENSITIVE TONE"
else:
sentiment_badge = "βšͺ NEUTRAL TONE"
summary_md = f"""
### 🎭 Primary Emotion: **{primary_emotion}** ({round(confidence * 100, 1)}%)
- **Overall Classification**: `{sentiment_badge}`
- **Analyzed Length**: `{len(text.split())}` words
- **Communication Tip**: {"Keep up the inspiring positive messaging!" if "POSITIVE" in sentiment_badge else "Consider softening critical words for a more constructive tone."}
"""
return primary_emotion, emotions_dict, summary_md
example_1 = "I am absolutely thrilled and grateful for this incredible opportunity! Everything turned out beyond my wildest dreams."
example_2 = "I feel so frustrated and disappointed with the unexpected delay. Nothing went according to schedule."
example_3 = "The meeting is scheduled for 3 PM in Conference Room B. Please bring the quarterly financial reports."
demo = gr.Blocks()
with demo:
gr.Markdown(
"""
# 🎭 NLP Emotion & Sentiment Studio
*Deep contextual emotion recognition powered by Transformers. Identifies Joy, Sadness, Anger, Fear, Surprise & Love.*
"""
)
with gr.Row():
with gr.Column(scale=1):
input_text = gr.Textbox(
label="Input Sentence or Paragraph",
placeholder="Enter text to analyze sentiment...",
lines=6
)
submit_btn = gr.Button("πŸ” Analyze Emotion & Tone", variant="primary")
gr.Examples(
examples=[[example_1], [example_2], [example_3]],
inputs=[input_text]
)
with gr.Column(scale=1):
out_primary = gr.Textbox(label="Top Detected Emotion")
out_label = gr.Label(label="Emotion Confidence Breakdown")
out_summary = gr.Markdown(label="Sentiment Summary")
submit_btn.click(
fn=analyze_emotion,
inputs=[input_text],
outputs=[out_primary, out_label, out_summary]
)
if __name__ == "__main__":
demo.launch()