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 "

Please enter more text.

", {} # 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"""
{info['emoji']}
{info['description']}
Confidence: {top['score']*100:.1f}%
""" 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()