File size: 7,216 Bytes
ef50856
 
91f79af
ef50856
4cb1fa5
14d7e08
ef50856
 
 
 
4cb1fa5
14d7e08
 
 
 
 
 
 
 
4cb1fa5
91f79af
003d031
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91f79af
 
ef50856
4cb1fa5
ef50856
91f79af
14d7e08
 
ef50856
003d031
91f79af
 
4cb1fa5
35fd465
91f79af
35fd465
91f79af
35fd465
003d031
 
91f79af
003d031
ef50856
4cb1fa5
 
 
 
003d031
 
 
 
 
 
 
14d7e08
ef50856
 
 
 
91f79af
14d7e08
003d031
14d7e08
003d031
14d7e08
ef50856
91f79af
14d7e08
003d031
 
14d7e08
ef50856
 
1b18d31
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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()