File size: 1,120 Bytes
2442d7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

# Load model
model_name = "textattack/bert-base-uncased-SST-2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)


def analyze_sentiment(text):
    inputs = tokenizer(text, return_tensors="pt",
                       truncation=True, padding=True)

    with torch.no_grad():
        outputs = model(**inputs)
        probs = torch.softmax(outputs.logits, dim=1)

    return {
        "POSITIVE": float(probs[0][1]),
        "NEGATIVE": float(probs[0][0])
    }


# Create interface
demo = gr.Interface(
    fn=analyze_sentiment,
    inputs=gr.Textbox(label="Input text", placeholder="Enter text here..."),
    outputs=gr.Label(label="Sentiment Probabilities"),
    examples=[
        ["I love this product!"],
        ["This was terrible experience"],
        ["It was okay, nothing special"]
    ],
    title="BERT Sentiment Analysis",
    description="Predicts sentiment using BERT model fine-tuned on SST-2 dataset"
)

demo.launch()