Spaces:
Running
Running
Update app.py
Browse filesUpdated version
app.py
CHANGED
@@ -2,13 +2,13 @@ import gradio as gr
|
|
2 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
3 |
from langdetect import detect
|
4 |
|
5 |
-
# Multilingual model
|
6 |
MODEL = "nlptown/bert-base-multilingual-uncased-sentiment"
|
7 |
tokenizer = AutoTokenizer.from_pretrained(MODEL)
|
8 |
model = AutoModelForSequenceClassification.from_pretrained(MODEL)
|
9 |
sentiment_model = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
|
10 |
|
11 |
-
#
|
12 |
STAR_EMOJIS = {
|
13 |
1: "😡 Very Negative",
|
14 |
2: "☹️ Negative",
|
@@ -17,79 +17,79 @@ STAR_EMOJIS = {
|
|
17 |
5: "🤩 Very Positive"
|
18 |
}
|
19 |
|
20 |
-
# Predefined actions
|
21 |
ACTIONS = {
|
22 |
'en': {
|
23 |
-
1: "Take a break, reflect
|
24 |
-
2: "Consider what
|
25 |
-
3: "Maintain balance;
|
26 |
4: "Share your positive experience and stay motivated!",
|
27 |
-
5: "Celebrate and spread your joy; keep up
|
28 |
},
|
29 |
'fr': {
|
30 |
-
1: "Faites une pause, réfléchissez
|
31 |
-
2: "
|
32 |
-
3: "Restez équilibré;
|
33 |
4: "Partagez votre expérience positive et restez motivé !",
|
34 |
-
5: "Célébrez et partagez votre joie
|
35 |
},
|
36 |
'de': {
|
37 |
-
1: "Machen Sie eine Pause, reflektieren Sie
|
38 |
-
2: "Überlegen Sie, was Sie stört, und
|
39 |
-
3: "Halten Sie das Gleichgewicht; Sie
|
40 |
4: "Teilen Sie Ihre positive Erfahrung und bleiben Sie motiviert!",
|
41 |
-
5: "Feiern Sie und verbreiten Sie Ihre Freude
|
42 |
},
|
43 |
'es': {
|
44 |
-
1: "Tómate un descanso, reflexiona
|
45 |
-
2: "Considera lo que te molesta y
|
46 |
-
3: "Mantén el equilibrio;
|
47 |
4: "Comparte tu experiencia positiva y mantente motivado!",
|
48 |
-
5: "Celebra y comparte tu alegría
|
49 |
},
|
50 |
'it': {
|
51 |
-
1: "Fai una pausa, rifletti
|
52 |
-
2: "Considera
|
53 |
-
3: "Mantieni l'equilibrio;
|
54 |
4: "Condividi la tua esperienza positiva e rimani motivato!",
|
55 |
-
5: "Festeggia e diffondi la tua gioia
|
56 |
},
|
57 |
'nl': {
|
58 |
-
1: "Neem een pauze,
|
59 |
-
2: "Overweeg wat je stoort en
|
60 |
-
3: "Behoud je balans;
|
61 |
4: "Deel je positieve ervaring en blijf gemotiveerd!",
|
62 |
-
5: "Vier en verspreid je vreugde
|
63 |
},
|
64 |
'pt': {
|
65 |
-
1: "Faça uma pausa, reflita
|
66 |
-
2: "Considere o que está incomodando e
|
67 |
-
3: "Mantenha o equilíbrio;
|
68 |
4: "Compartilhe sua experiência positiva e mantenha-se motivado!",
|
69 |
-
5: "Celebre e espalhe sua alegria
|
70 |
},
|
71 |
'ru': {
|
72 |
1: "Сделайте перерыв, обдумайте ситуацию или обратитесь за поддержкой.",
|
73 |
-
2: "Подумайте, что вас беспокоит, и
|
74 |
-
3: "Сохраняйте баланс;
|
75 |
4: "Поделитесь положительным опытом и оставайтесь мотивированными!",
|
76 |
-
5: "Празднуйте и распространяйте
|
77 |
},
|
78 |
'ar': {
|
79 |
-
1: "خذ استراحة،
|
80 |
-
2: "فكر فيما يزعجك
|
81 |
-
3: "حافظ على توازنك؛
|
82 |
4: "شارك تجربتك الإيجابية وابقَ متحمسًا!",
|
83 |
-
5: "احتفل وانشر
|
84 |
},
|
85 |
'ja': {
|
86 |
1: "休憩を取り、状況を振り返るかサポートを求めてください。",
|
87 |
-
2: "
|
88 |
-
3: "
|
89 |
4: "ポジティブな体験を共有し、モチベーションを維持してください!",
|
90 |
-
5: "
|
91 |
},
|
92 |
-
'yo': {
|
93 |
1: "Sinmi, ronú lórí ohun tó ṣẹlẹ̀, tàbí wa ìrànlọ́wọ́.",
|
94 |
2: "Ronú nípa ohun tó ń dá ọ lẹ́rù, kí o sì gbìmọ̀ láti ṣe atunṣe.",
|
95 |
3: "Dá a lára, o wà lórí ìṣàkóso, tẹ̀síwájú bí ó ṣe wà.",
|
@@ -99,15 +99,16 @@ ACTIONS = {
|
|
99 |
}
|
100 |
|
101 |
def analyze_sentiment(text):
|
102 |
-
# Sentiment
|
103 |
result = sentiment_model(text)[0]
|
104 |
stars = int(result["label"][0])
|
105 |
sentiment = STAR_EMOJIS.get(stars, result["label"])
|
106 |
confidence = f"{result['score']:.2f}"
|
107 |
|
108 |
-
#
|
109 |
try:
|
110 |
lang = detect(text)
|
|
|
111 |
lang = lang if lang in ACTIONS else 'en'
|
112 |
except:
|
113 |
lang = 'en'
|
@@ -115,14 +116,13 @@ def analyze_sentiment(text):
|
|
115 |
action = ACTIONS[lang].get(stars, "")
|
116 |
return [[sentiment, confidence, action]]
|
117 |
|
118 |
-
# Examples
|
119 |
examples = [
|
120 |
-
["I absolutely love this new phone
|
121 |
-
["Mo nifẹ́ fíìmù yìí gan-an!"],
|
122 |
-
["
|
123 |
-
["
|
124 |
-
["
|
125 |
-
["Este producto es muy malo y no funciona."], # Spanish
|
126 |
]
|
127 |
|
128 |
# Gradio UI
|
@@ -137,9 +137,7 @@ demo = gr.Interface(
|
|
137 |
examples=examples,
|
138 |
title="🌍 Multilingual Emotion & Action Analyzer",
|
139 |
description=(
|
140 |
-
"Supports 11+ languages
|
141 |
-
"Portuguese, Russian, Arabic, Japanese, Yoruba. Detects emotion (1–5 stars) and provides "
|
142 |
-
"suggested actions in the input language."
|
143 |
),
|
144 |
)
|
145 |
|
|
|
2 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
3 |
from langdetect import detect
|
4 |
|
5 |
+
# Multilingual sentiment model
|
6 |
MODEL = "nlptown/bert-base-multilingual-uncased-sentiment"
|
7 |
tokenizer = AutoTokenizer.from_pretrained(MODEL)
|
8 |
model = AutoModelForSequenceClassification.from_pretrained(MODEL)
|
9 |
sentiment_model = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
|
10 |
|
11 |
+
# Star emojis for sentiment
|
12 |
STAR_EMOJIS = {
|
13 |
1: "😡 Very Negative",
|
14 |
2: "☹️ Negative",
|
|
|
17 |
5: "🤩 Very Positive"
|
18 |
}
|
19 |
|
20 |
+
# Predefined "What to do" actions per language
|
21 |
ACTIONS = {
|
22 |
'en': {
|
23 |
+
1: "Take a break, reflect, or seek support.",
|
24 |
+
2: "Consider what's bothering you and address it calmly.",
|
25 |
+
3: "Maintain balance; continue as usual.",
|
26 |
4: "Share your positive experience and stay motivated!",
|
27 |
+
5: "Celebrate and spread your joy; keep up enthusiasm!"
|
28 |
},
|
29 |
'fr': {
|
30 |
+
1: "Faites une pause, réfléchissez ou demandez de l'aide.",
|
31 |
+
2: "Réfléchissez à ce qui vous dérange et agissez calmement.",
|
32 |
+
3: "Restez équilibré; continuez comme d'habitude.",
|
33 |
4: "Partagez votre expérience positive et restez motivé !",
|
34 |
+
5: "Célébrez et partagez votre joie avec enthousiasme !"
|
35 |
},
|
36 |
'de': {
|
37 |
+
1: "Machen Sie eine Pause, reflektieren Sie oder suchen Sie Unterstützung.",
|
38 |
+
2: "Überlegen Sie, was Sie stört, und lösen Sie es ruhig.",
|
39 |
+
3: "Halten Sie das Gleichgewicht; fahren Sie fort wie gewohnt.",
|
40 |
4: "Teilen Sie Ihre positive Erfahrung und bleiben Sie motiviert!",
|
41 |
+
5: "Feiern Sie und verbreiten Sie Ihre Freude enthusiastisch!"
|
42 |
},
|
43 |
'es': {
|
44 |
+
1: "Tómate un descanso, reflexiona o busca apoyo.",
|
45 |
+
2: "Considera lo que te molesta y actúa con calma.",
|
46 |
+
3: "Mantén el equilibrio; continúa como de costumbre.",
|
47 |
4: "Comparte tu experiencia positiva y mantente motivado!",
|
48 |
+
5: "Celebra y comparte tu alegría con entusiasmo!"
|
49 |
},
|
50 |
'it': {
|
51 |
+
1: "Fai una pausa, rifletti o cerca supporto.",
|
52 |
+
2: "Considera ciò che ti infastidisce e affrontalo con calma.",
|
53 |
+
3: "Mantieni l'equilibrio; continua come al solito.",
|
54 |
4: "Condividi la tua esperienza positiva e rimani motivato!",
|
55 |
+
5: "Festeggia e diffondi la tua gioia con entusiasmo!"
|
56 |
},
|
57 |
'nl': {
|
58 |
+
1: "Neem een pauze, reflecteer of zoek ondersteuning.",
|
59 |
+
2: "Overweeg wat je stoort en handel rustig.",
|
60 |
+
3: "Behoud je balans; ga door zoals gewoonlijk.",
|
61 |
4: "Deel je positieve ervaring en blijf gemotiveerd!",
|
62 |
+
5: "Vier en verspreid je vreugde enthousiast!"
|
63 |
},
|
64 |
'pt': {
|
65 |
+
1: "Faça uma pausa, reflita ou busque apoio.",
|
66 |
+
2: "Considere o que está incomodando e resolva calmamente.",
|
67 |
+
3: "Mantenha o equilíbrio; continue normalmente.",
|
68 |
4: "Compartilhe sua experiência positiva e mantenha-se motivado!",
|
69 |
+
5: "Celebre e espalhe sua alegria com entusiasmo!"
|
70 |
},
|
71 |
'ru': {
|
72 |
1: "Сделайте перерыв, обдумайте ситуацию или обратитесь за поддержкой.",
|
73 |
+
2: "Подумайте, что вас беспокоит, и решайте спокойно.",
|
74 |
+
3: "Сохраняйте баланс; продолжайте как обычно.",
|
75 |
4: "Поделитесь положительным опытом и оставайтесь мотивированными!",
|
76 |
+
5: "Празднуйте и распространяйте радость с энтузиазмом!"
|
77 |
},
|
78 |
'ar': {
|
79 |
+
1: "خذ استراحة، تأمل، أو اطلب الدعم.",
|
80 |
+
2: "فكر فيما يزعجك وتعامل معه بهدوء.",
|
81 |
+
3: "حافظ على توازنك؛ استمر كالمعتاد.",
|
82 |
4: "شارك تجربتك الإيجابية وابقَ متحمسًا!",
|
83 |
+
5: "احتفل وانشر فرحك بحماس!"
|
84 |
},
|
85 |
'ja': {
|
86 |
1: "休憩を取り、状況を振り返るかサポートを求めてください。",
|
87 |
+
2: "何が不満か考え、冷静に対処してください。",
|
88 |
+
3: "バランスを保ち、通常通り続けてください。",
|
89 |
4: "ポジティブな体験を共有し、モチベーションを維持してください!",
|
90 |
+
5: "喜びを祝福し、熱意をもって広めましょう!"
|
91 |
},
|
92 |
+
'yo': {
|
93 |
1: "Sinmi, ronú lórí ohun tó ṣẹlẹ̀, tàbí wa ìrànlọ́wọ́.",
|
94 |
2: "Ronú nípa ohun tó ń dá ọ lẹ́rù, kí o sì gbìmọ̀ láti ṣe atunṣe.",
|
95 |
3: "Dá a lára, o wà lórí ìṣàkóso, tẹ̀síwájú bí ó ṣe wà.",
|
|
|
99 |
}
|
100 |
|
101 |
def analyze_sentiment(text):
|
102 |
+
# Sentiment analysis
|
103 |
result = sentiment_model(text)[0]
|
104 |
stars = int(result["label"][0])
|
105 |
sentiment = STAR_EMOJIS.get(stars, result["label"])
|
106 |
confidence = f"{result['score']:.2f}"
|
107 |
|
108 |
+
# Language detection with Yoruba mapping
|
109 |
try:
|
110 |
lang = detect(text)
|
111 |
+
lang = 'yo' if lang == 'yo' else lang
|
112 |
lang = lang if lang in ACTIONS else 'en'
|
113 |
except:
|
114 |
lang = 'en'
|
|
|
116 |
action = ACTIONS[lang].get(stars, "")
|
117 |
return [[sentiment, confidence, action]]
|
118 |
|
119 |
+
# Examples for testing
|
120 |
examples = [
|
121 |
+
["I absolutely love this new phone!"], # English
|
122 |
+
["Mo nifẹ́ fíìmù yìí gan-an!"], # Yoruba
|
123 |
+
["Je déteste quand cette application plante."], # French
|
124 |
+
["Das Essen in diesem Restaurant war fantastisch!"], # German
|
125 |
+
["Este producto es muy malo."], # Spanish
|
|
|
126 |
]
|
127 |
|
128 |
# Gradio UI
|
|
|
137 |
examples=examples,
|
138 |
title="🌍 Multilingual Emotion & Action Analyzer",
|
139 |
description=(
|
140 |
+
"Supports 11+ languages. Detects emotion (1–5 stars) and provides suggested actions in the input language."
|
|
|
|
|
141 |
),
|
142 |
)
|
143 |
|