File size: 1,179 Bytes
784b06e
 
 
 
 
 
 
 
 
 
 
 
 
 
226a57a
784b06e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 25 14:10:33 2025

@author: shuangshuang
"""

from transformers import pipeline
import gradio as gr

# Load model
classifier = pipeline(
    "sentiment-analysis",
    model="nlptown/bert-base-multilingual-uncased-sentiment",
    # device=-1,
)

# Map labels
label_map = {
    "1 star": "very bad",
    "2 stars": "bad",
    "3 stars": "neutral",
    "4 stars": "good",
    "5 stars": "very good",
}


# Prediction function
def predict(text):
    text = text.strip()
    if not text:
        return "Please enter some text."
    result = classifier(text)[0]
    label = result["label"]
    score = result["score"]
    mapped = label_map[label]
    return f"Prediction: {mapped}\nConfidence: {score:.2f}"


# Gradio interface
interface = gr.Interface(
    fn=predict,
    inputs=gr.Textbox(lines=2, placeholder="Enter a sentence..."),
    outputs="text",
    title="Sentiment Analysis",
    description="Enter a sentence to analyze its sentiment.",
    examples=["I love this product!", "This is terrible."],
)

# Launch (Hugging Face Spaces doesn't need special params)
if __name__ == "__main__":
    interface.launch(ssr_mode=False)