Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline | |
| from langdetect import detect | |
| # Multilingual sentiment model | |
| 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) | |
| # Star emojis for sentiment | |
| STAR_EMOJIS = { | |
| 1: "😡 Very Negative", | |
| 2: "☹️ Negative", | |
| 3: "😐 Neutral", | |
| 4: "🙂 Positive", | |
| 5: "🤩 Very Positive" | |
| } | |
| # Predefined "What to do" actions per language | |
| ACTIONS = { | |
| 'en': {1: "Take a break, reflect, or seek support.", | |
| 2: "Consider what's bothering you and address it calmly.", | |
| 3: "Maintain balance; continue as usual.", | |
| 4: "Share your positive experience and stay motivated!", | |
| 5: "Celebrate and spread your joy; keep up enthusiasm!"}, | |
| 'fr': {1: "Faites une pause, réfléchissez ou demandez de l'aide.", | |
| 2: "Réfléchissez à ce qui vous dérange et agissez calmement.", | |
| 3: "Restez équilibré; continuez comme d'habitude.", | |
| 4: "Partagez votre expérience positive et restez motivé !", | |
| 5: "Célébrez et partagez votre joie avec enthousiasme !"}, | |
| 'de': {1: "Machen Sie eine Pause, reflektieren Sie oder suchen Sie Unterstützung.", | |
| 2: "Überlegen Sie, was Sie stört, und lösen Sie es ruhig.", | |
| 3: "Halten Sie das Gleichgewicht; fahren Sie fort wie gewohnt.", | |
| 4: "Teilen Sie Ihre positive Erfahrung und bleiben Sie motiviert!", | |
| 5: "Feiern Sie und verbreiten Sie Ihre Freude enthusiastisch!"}, | |
| 'es': {1: "Tómate un descanso, reflexiona o busca apoyo.", | |
| 2: "Considera lo que te molesta y actúa con calma.", | |
| 3: "Mantén el equilibrio; continúa como de costumbre.", | |
| 4: "Comparte tu experiencia positiva y mantente motivado!", | |
| 5: "Celebra y comparte tu alegría con entusiasmo!"}, | |
| 'it': {1: "Fai una pausa, rifletti o cerca supporto.", | |
| 2: "Considera ciò che ti infastidisce e affrontalo con calma.", | |
| 3: "Mantieni l'equilibrio; continua come al solito.", | |
| 4: "Condividi la tua esperienza positiva e rimani motivato!", | |
| 5: "Festeggia e diffondi la tua gioia con entusiasmo!"}, | |
| 'nl': {1: "Neem een pauze, reflecteer of zoek ondersteuning.", | |
| 2: "Overweeg wat je stoort en handel rustig.", | |
| 3: "Behoud je balans; ga door zoals gewoonlijk.", | |
| 4: "Deel je positieve ervaring en blijf gemotiveerd!", | |
| 5: "Vier en verspreid je vreugde enthousiast!"}, | |
| 'pt': {1: "Faça uma pausa, reflita ou busque apoio.", | |
| 2: "Considere o que está incomodando e resolva calmamente.", | |
| 3: "Mantenha o equilíbrio; continue normalmente.", | |
| 4: "Compartilhe sua experiência positiva e mantenha-se motivado!", | |
| 5: "Celebre e espalhe sua alegria com entusiasmo!"}, | |
| 'ru': {1: "Сделайте перерыв, обдумайте ситуацию или обратитесь за поддержкой.", | |
| 2: "Подумайте, что вас беспокоит, и решайте спокойно.", | |
| 3: "Сохраняйте баланс; продолжайте как обычно.", | |
| 4: "Поделитесь положительным опытом и оставайтесь мотивированными!", | |
| 5: "Празднуйте и распространяйте радость с энтузиазмом!"}, | |
| 'ar': {1: "خذ استراحة، تأمل، أو اطلب الدعم.", | |
| 2: "فكر فيما يزعجك وتعامل معه بهدوء.", | |
| 3: "حافظ على توازنك؛ استمر كالمعتاد.", | |
| 4: "شارك تجربتك الإيجابية وابقَ متحمسًا!", | |
| 5: "احتفل وانشر فرحك بحماس!"}, | |
| 'ja': {1: "休憩を取り、状況を振り返るかサポートを求めてください。", | |
| 2: "何が不満か考え、冷静に対処してください。", | |
| 3: "バランスを保ち、通常通り続けてください。", | |
| 4: "ポジティブな体験を共有し、モチベーションを維持してください!", | |
| 5: "喜びを祝福し、熱意をもって広めましょう!"}, | |
| 'yo': {1: "Sinmi, ronú lórí ohun tó ṣẹlẹ̀, tàbí wa ìrànlọ́wọ́.", | |
| 2: "Ronú nípa ohun tó ń dá ọ lẹ́rù, kí o sì gbìmọ̀ láti ṣe atunṣe.", | |
| 3: "Dá a lára, o wà lórí ìṣàkóso, tẹ̀síwájú bí ó ṣe wà.", | |
| 4: "Pín ìrírí rẹ tó dáa kí o sì máa ní ìmọ̀lára rere!", | |
| 5: "Ṣe ayẹyẹ, tàn ìdùnnú rẹ kaakiri, tẹ̀síwájú pẹ̀lú ìfẹ́!"} | |
| } | |
| # Map language codes to readable names | |
| LANG_NAMES = { | |
| 'en': 'English', 'fr': 'French', 'de': 'German', 'es': 'Spanish', 'it': 'Italian', | |
| 'nl': 'Dutch', 'pt': 'Portuguese', 'ru': 'Russian', 'ar': 'Arabic', 'ja': 'Japanese', | |
| 'yo': 'Yoruba' | |
| } | |
| def analyze_sentiment(text): | |
| # Sentiment analysis | |
| result = sentiment_model(text)[0] | |
| stars = int(result["label"][0]) | |
| sentiment = STAR_EMOJIS.get(stars, result["label"]) | |
| confidence = f"{result['score']:.2f}" | |
| # Language detection | |
| try: | |
| lang = detect(text) | |
| lang = 'yo' if lang == 'yo' else lang | |
| lang = lang if lang in ACTIONS else 'en' | |
| except: | |
| lang = 'en' | |
| action = ACTIONS[lang].get(stars, "") | |
| lang_name = LANG_NAMES.get(lang, "Unknown") | |
| return [[sentiment, confidence, action, lang_name]] | |
| # Examples covering all 11 languages | |
| examples = [ | |
| ["I absolutely love this new phone!"], # English | |
| ["Je déteste quand cette application plante."], # French | |
| ["Das Essen in diesem Restaurant war fantastisch!"], # German | |
| ["Este producto es muy malo."], # Spanish | |
| ["Questo film è stato noioso e troppo lungo."], # Italian | |
| ["De app werkt prima, maar kan beter."], # Dutch | |
| ["Eu gostei muito do serviço, foi excelente!"], # Portuguese | |
| ["Эта книга ужасна, я еле её дочитал."], # Russian | |
| ["هذا الهاتف رائع للغاية، أنا سعيد جدًا به."], # Arabic | |
| ["この映画は本当に面白かった!"], # Japanese | |
| ["Mo nifẹ́ fíìmù yìí gan-an!"] # Yoruba | |
| ] | |
| # Gradio UI | |
| demo = gr.Interface( | |
| fn=analyze_sentiment, | |
| inputs=gr.Textbox(lines=3, placeholder="Type a sentence in any supported language..."), | |
| outputs=gr.Dataframe( | |
| headers=["Emotion (1–5 Stars)", "Confidence", "What to do", "Language Detected"], | |
| row_count=1, | |
| col_count=(4, "fixed"), | |
| ), | |
| examples=examples, | |
| title="🌍 Multilingual Emotion & Action Analyzer", | |
| description=( | |
| "Supports 11 languages. Detects emotion (1–5 stars), provides suggested actions in the input language, " | |
| "and shows which language was detected." | |
| ), | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |