import gradio as gr from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline # Multilingual model (10+ languages) MODEL = "nlptown/bert-base-multilingual-uncased-sentiment" tokenizer = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForSequenceClassification.from_pretrained(MODEL) sentiment_model = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer) # Map stars (1–5) to emotion labels with emojis STAR_EMOJIS = { 1: "😡 Very Negative", 2: "☹️ Negative", 3: "😐 Neutral", 4: "🙂 Positive", 5: "🤩 Very Positive" } def analyze_sentiment(text): result = sentiment_model(text)[0] stars = int(result["label"][0]) # "1 star" → 1 sentiment = STAR_EMOJIS.get(stars, result["label"]) confidence = f"{result['score']:.2f}" return [[sentiment, confidence]] # Example texts in different languages including Yoruba examples = [ ["I absolutely love this new phone, the camera is stunning!"], # English ["Je déteste quand cette application plante sans cesse."], # French ["Das Essen in diesem Restaurant war fantastisch!"], # German ["Este producto es muy malo y no funciona."], # Spanish ["Questo film è stato noioso e troppo lungo."], # Italian ["Eu gostei muito do serviço, foi excelente!"], # Portuguese ["Эта книга ужасна, я еле её дочитал."], # Russian ["هذا الهاتف رائع للغاية، أنا سعيد جدًا به."], # Arabic ["この映画は本当に面白かった!"], # Japanese ["De app werkt prima, maar kan beter."], # Dutch ["Mo nifẹ́ fíìmù yìí gan-an!"], # Yoruba Positive ["Mo kọ́ láti rí ìrírí tó dáa nínú iṣẹ́ yìí."], # Yoruba Neutral ["Mo bínú gan-an sí ìṣẹ̀lẹ̀ náà."], # Yoruba Negative ] # Gradio UI demo = gr.Interface( fn=analyze_sentiment, inputs=gr.Textbox(lines=3, placeholder="Type a sentence here in one of 11+ languages..."), outputs=gr.Dataframe( headers=["Emotion (1–5 Stars)", "Confidence"], row_count=1, col_count=(2, "fixed"), ), examples=examples, title="🌍 Multilingual Emotion & Sentiment Analyzer", description=( "Supports 11+ languages (English, French, German, Spanish, Italian, Dutch, " "Portuguese, Russian, Arabic, Japanese, Yoruba). Detects fine-grained emotions " "with 5 levels:\n\n" "😡 Very Negative | ☹️ Negative | 😐 Neutral | 🙂 Positive | 🤩 Very Positive" ), ) if __name__ == "__main__": demo.launch()