File size: 1,154 Bytes
ae8c22d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import gradio as gr
from transformers import pipeline

# 3-class model (negative / neutral / positive)
MODEL_ID = "cardiffnlp/twitter-roberta-base-sentiment-latest"
sentiment_pipeline = pipeline("sentiment-analysis", model=MODEL_ID)

LABEL_MAP = {
    "LABEL_0": "Negative",
    "LABEL_1": "Neutral",
    "LABEL_2": "Positive",
    "NEGATIVE": "Negative",
    "NEUTRAL": "Neutral",
    "POSITIVE": "Positive",
}

def analyze_sentiment(text):
    text = (text or "").strip()
    if not text:
        return "⚠️ Please enter some text."
    result = sentiment_pipeline(text, truncation=True)[0]
    label = LABEL_MAP.get(result["label"], result["label"].title())
    score = round(float(result["score"]), 3)
    return f"{label}  (confidence: {score})"

demo = gr.Interface(
    fn=analyze_sentiment,
    inputs=gr.Textbox(lines=3, placeholder="Type a sentence here..."),
    outputs="text",
    title="Sentiment Analyzer",
    description="Classifies text as Negative, Neutral, or Positive using a Hugging Face transformer.",
    examples=[["I love this!"], ["This is okay, I guess."], ["I hate it."]],
)

if __name__ == "__main__":
    demo.launch()