File size: 2,325 Bytes
46b12e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import gradio as gr
import requests
import os

# ---------- CONFIG ----------
# We'll use the free Inference API – no local model downloads.
# Get your token from https://huggingface.co/settings/tokens
# Add it as a Space secret named "HF_TOKEN"
HF_TOKEN = os.getenv("HF_TOKEN")
API_URL = "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english"

headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}

# ---------- FUNCTION ----------
def analyze_sentiment(text):
    """Send text to the model and return the sentiment label + score."""
    if not text.strip():
        return "⚠️ Please enter some text."

    # If no token is set, show a friendly error.
    if not HF_TOKEN:
        return "🔑 Please set your HF_TOKEN as a Space secret."

    payload = {"inputs": text}

    try:
        response = requests.post(API_URL, headers=headers, json=payload)
        response.raise_for_status()  # raise if HTTP error

        # The API returns a list of predictions: [{'label': 'POSITIVE', 'score': 0.99}, ...]
        result = response.json()
        # The first element is the list of predictions for the first input.
        # For this model, it returns a list of two dicts: one for NEGATIVE, one for POSITIVE.
        # We'll pick the one with highest score.
        predictions = result[0]  # list of dicts
        best = max(predictions, key=lambda x: x['score'])
        label = best['label']
        score = best['score']

        return f"**{label}** (confidence: {score:.2%})"

    except requests.exceptions.RequestException as e:
        return f"❌ API error: {str(e)}"


# ---------- GRADIO INTERFACE ----------
demo = gr.Interface(
    fn=analyze_sentiment,
    inputs=gr.Textbox(
        label="Enter your text",
        placeholder="I love Hugging Face Spaces!",
        lines=3
    ),
    outputs=gr.Markdown(label="Sentiment result"),
    title="😊 Sentiment Analyzer",
    description="Enter any text and get a sentiment prediction (positive/negative). Powered by DistilBERT.",
    examples=[
        ["This product is amazing!"],
        ["I'm really disappointed with the service."],
        ["The movie was okay, nothing special."],
    ],
    theme="huggingface",
)

# ---------- RUN ----------
if __name__ == "__main__":
    demo.launch()