sentiment / app.py
samandar1105's picture
Update app.py
5f4e3c9 verified
Raw
History Blame Contribute Delete
2.86 kB
import gradio as gr
from transformers import pipeline
import torch
MODEL_ID = "samandar1105/sentiment-classifier"
LABEL_INFO = {
"positive": {"emoji": "😊", "description": "Positive Sentiment", "color": "#22c55e"},
"negative": {"emoji": "😞", "description": "Negative Sentiment", "color": "#ef4444"},
}
EXAMPLES = [
["This movie was absolutely breathtaking. One of the best I have ever seen."],
["Terrible experience. The product broke after one day."],
["I cannot recommend this highly enough β€” outstanding quality!"],
["What a disappointment. The movie was boring."],
]
classifier = pipeline(
"text-classification",
model=MODEL_ID,
top_k=None
)
def analyze_sentiment(text):
if not text or len(text.strip()) < 5:
return "<p>Please enter more text.</p>", {}
# Get all class scores
result = classifier(text[:512])
# Handle different output formats
scores = result[0] if isinstance(result[0], list) else result
# Sort by confidence
scores = sorted(scores, key=lambda x: x["score"], reverse=True)
top = scores[0]
info = LABEL_INFO[top["label"]]
html = f"""
<div style="padding:20px;border-radius:12px;
background:{info['color']}18;
border:2px solid {info['color']};
text-align:center;">
<div style="font-size:48px;">{info['emoji']}</div>
<div style="font-size:24px;font-weight:bold;color:{info['color']};">
{info['description']}
</div>
<div style="font-size:18px;">
Confidence: <strong>{top['score']*100:.1f}%</strong>
</div>
</div>
"""
conf = {
f"{LABEL_INFO[s['label']]['emoji']} {s['label'].capitalize()}": round(s["score"], 4)
for s in scores
}
return html, conf
with gr.Blocks(title="Sentiment Analyzer", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🎭 Sentiment Analyzer\nPaste any English text to detect **positive 😊** or **negative 😞** sentiment.")
with gr.Row():
with gr.Column(scale=3):
input_text = gr.Textbox(label="πŸ“ Your Text", placeholder="Type or paste text here...", lines=6)
with gr.Row():
analyze_btn = gr.Button("πŸ” Analyze Sentiment", variant="primary", scale=3)
gr.ClearButton([input_text], scale=1)
with gr.Column(scale=2):
result_html = gr.HTML(label="Result")
confidence = gr.Label(label="πŸ“Š Confidence Scores", num_top_classes=2)
gr.Examples(examples=EXAMPLES, inputs=input_text, label="πŸ’‘ Click an example")
analyze_btn.click(fn=analyze_sentiment, inputs=[input_text], outputs=[result_html, confidence])
input_text.submit(fn=analyze_sentiment, inputs=[input_text], outputs=[result_html, confidence])
if __name__ == "__main__":
demo.launch()