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

MODEL_NAME = "nlptown/bert-base-multilingual-uncased-sentiment"
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)

LABELS = {
    0: "Very Negative",
    1: "Negative",
    2: "Neutral",
    3: "Positive",
    4: "Very Positive"
}

def predict_sentiment(text):
    inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
    outputs = model(**inputs)
    probs = torch.nn.functional.softmax(outputs.logits, dim=1)
    confidence, prediction = torch.max(probs, dim=1)
    sentiment = LABELS[prediction.item()]
    return {
        "Sentiment feeling": sentiment,
        "Confidence score": f"{confidence.item():.3f} ({'Highly Certain' if confidence.item() > 0.8 else 'Somewhat Certain' if confidence.item() > 0.6 else 'Uncertain'})"
    }

iface = gr.Interface(
    fn=predict_sentiment,
    inputs=gr.Textbox(lines=2, placeholder="Enter text (any language)..."),
    outputs="json",
    title="🌍 Multilingual Sentiment Analysis",
    description="Check your text's sentiment instantly using a multilingual BERT model trained on reviews. Supports languages like English, Spanish, French, German, etc.",
    theme="soft",
    allow_flagging="never"
)

iface.launch()