| 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() |