Spaces:
Sleeping
Sleeping
| 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() | |