sehanlim's picture
Initial sentiment analyzer demo
8984983 verified
Raw History Blame Contribute Delete
2.41 kB
import gradio as gr
from transformers import pipeline
# Load sentiment analysis pipeline
classifier = pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english",
return_all_scores=True
)
def analyze_sentiment(text):
"""Analyze sentiment and return percentages."""
if not text.strip():
return {"Positive": 0, "Negative": 0, "Neutral": 0}, ""
results = classifier(text)[0]
# Convert to percentage format
sentiment_map = {}
for r in results:
label = r['label']
score = r['score'] * 100
if label == 'POSITIVE':
sentiment_map['Positive'] = round(score, 2)
elif label == 'NEGATIVE':
sentiment_map['Negative'] = round(score, 2)
# Add neutral if needed (for models that only have pos/neg)
if 'Neutral' not in sentiment_map:
sentiment_map['Neutral'] = round(100 - sentiment_map.get('Positive', 0) - sentiment_map.get('Negative', 0), 2)
# Create summary text
dominant = max(sentiment_map, key=sentiment_map.get)
summary = f"**Dominant: {dominant} ({sentiment_map[dominant]}%)**"
return sentiment_map, summary
# Create Gradio interface
with gr.Blocks(title="Simple Sentiment Analyzer") as demo:
gr.Markdown("# 🎭 Simple Sentiment Analyzer")
gr.Markdown("Enter a sentence to see sentiment breakdown with percentages.")
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
label="Input Text",
placeholder="Type your sentence here...",
lines=4
)
analyze_btn = gr.Button("Analyze", variant="primary")
with gr.Column():
output_json = gr.Label(label="Sentiment Scores (%)", num_top_classes=3)
summary_md = gr.Markdown()
analyze_btn.click(
fn=analyze_sentiment,
inputs=text_input,
outputs=[output_json, summary_md]
)
# Example inputs
gr.Examples(
examples=[
"I absolutely love this product! It's amazing!",
"This is terrible. I hate it.",
"The weather is okay today.",
"The movie was okay, nothing special but not bad either.",
"Best day ever! Everything went perfectly!"
],
inputs=text_input
)
if __name__ == "__main__":
demo.launch()