anabury commited on
Commit
003d031
·
verified ·
1 Parent(s): 4cb1fa5

Update app.py

Browse files

Updated Version

Files changed (1) hide show
  1. app.py +77 -84
app.py CHANGED
@@ -19,83 +19,68 @@ STAR_EMOJIS = {
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à.",
96
- 4: "Pín ìrírí rẹ tó dáa kí o sì máa ní ìmọ̀lára rere!",
97
- 5: "Ṣe ayẹyẹ, tàn ìdùnnú rẹ kaakiri, tẹ̀síwájú pẹ̀lú ìfẹ́!"
98
- }
99
  }
100
 
101
  def analyze_sentiment(text):
@@ -105,7 +90,7 @@ def analyze_sentiment(text):
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
@@ -114,15 +99,22 @@ def analyze_sentiment(text):
114
  lang = 'en'
115
 
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
@@ -130,14 +122,15 @@ demo = gr.Interface(
130
  fn=analyze_sentiment,
131
  inputs=gr.Textbox(lines=3, placeholder="Type a sentence in any supported language..."),
132
  outputs=gr.Dataframe(
133
- headers=["Emotion (1–5 Stars)", "Confidence", "What to do"],
134
  row_count=1,
135
- col_count=(3, "fixed"),
136
  ),
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
 
 
19
 
20
  # Predefined "What to do" actions per language
21
  ACTIONS = {
22
+ 'en': {1: "Take a break, reflect, or seek support.",
23
+ 2: "Consider what's bothering you and address it calmly.",
24
+ 3: "Maintain balance; continue as usual.",
25
+ 4: "Share your positive experience and stay motivated!",
26
+ 5: "Celebrate and spread your joy; keep up enthusiasm!"},
27
+ 'fr': {1: "Faites une pause, réfléchissez ou demandez de l'aide.",
28
+ 2: "Réfléchissez à ce qui vous dérange et agissez calmement.",
29
+ 3: "Restez équilibré; continuez comme d'habitude.",
30
+ 4: "Partagez votre expérience positive et restez motivé !",
31
+ 5: "Célébrez et partagez votre joie avec enthousiasme !"},
32
+ 'de': {1: "Machen Sie eine Pause, reflektieren Sie oder suchen Sie Unterstützung.",
33
+ 2: "Überlegen Sie, was Sie stört, und lösen Sie es ruhig.",
34
+ 3: "Halten Sie das Gleichgewicht; fahren Sie fort wie gewohnt.",
35
+ 4: "Teilen Sie Ihre positive Erfahrung und bleiben Sie motiviert!",
36
+ 5: "Feiern Sie und verbreiten Sie Ihre Freude enthusiastisch!"},
37
+ 'es': {1: "Tómate un descanso, reflexiona o busca apoyo.",
38
+ 2: "Considera lo que te molesta y actúa con calma.",
39
+ 3: "Mantén el equilibrio; continúa como de costumbre.",
40
+ 4: "Comparte tu experiencia positiva y mantente motivado!",
41
+ 5: "Celebra y comparte tu alegría con entusiasmo!"},
42
+ 'it': {1: "Fai una pausa, rifletti o cerca supporto.",
43
+ 2: "Considera ciò che ti infastidisce e affrontalo con calma.",
44
+ 3: "Mantieni l'equilibrio; continua come al solito.",
45
+ 4: "Condividi la tua esperienza positiva e rimani motivato!",
46
+ 5: "Festeggia e diffondi la tua gioia con entusiasmo!"},
47
+ 'nl': {1: "Neem een pauze, reflecteer of zoek ondersteuning.",
48
+ 2: "Overweeg wat je stoort en handel rustig.",
49
+ 3: "Behoud je balans; ga door zoals gewoonlijk.",
50
+ 4: "Deel je positieve ervaring en blijf gemotiveerd!",
51
+ 5: "Vier en verspreid je vreugde enthousiast!"},
52
+ 'pt': {1: "Faça uma pausa, reflita ou busque apoio.",
53
+ 2: "Considere o que está incomodando e resolva calmamente.",
54
+ 3: "Mantenha o equilíbrio; continue normalmente.",
55
+ 4: "Compartilhe sua experiência positiva e mantenha-se motivado!",
56
+ 5: "Celebre e espalhe sua alegria com entusiasmo!"},
57
+ 'ru': {1: "Сделайте перерыв, обдумайте ситуацию или обратитесь за поддержкой.",
58
+ 2: "Подумайте, что вас беспокоит, и решайте спокойно.",
59
+ 3: "Сохраняйте баланс; продолжайте как обычно.",
60
+ 4: "Поделитесь положительным опытом и оставайтесь мотивированными!",
61
+ 5: "Празднуйте и распространяйте радость с энтузиазмом!"},
62
+ 'ar': {1: "خذ استراحة، تأمل، أو اطلب الدعم.",
63
+ 2: "فكر فيما يزعجك وتعامل معه بهدوء.",
64
+ 3: "حافظ على توازنك؛ استمر كالمعتاد.",
65
+ 4: "شارك تجربتك الإيجابية وابقَ متحمسًا!",
66
+ 5: "احتفل وانشر فرحك بحماس!"},
67
+ 'ja': {1: "休憩を取り、状況を振り返るかサポートを求めてください。",
68
+ 2: "何が不満か考え、冷静に対処してください。",
69
+ 3: "バランスを保ち、通常通り続けてください。",
70
+ 4: "ポジティブな体験を共有し、モチベーションを維持してください!",
71
+ 5: "喜びを祝福し、熱意をもって広めましょう!"},
72
+ 'yo': {1: "Sinmi, ronú lórí ohun ṣẹlẹ̀, tàbí wa ìrànlọ́wọ́.",
73
+ 2: "Ronú nípa ohun ń ọ lẹ́rù, kí o sì gbìmọ̀ láti ṣe atunṣe.",
74
+ 3: " a lára, o wà lórí ìṣàkóso, tẹ̀síwájú bí ó ṣe wà.",
75
+ 4: "Pín ìrírí rẹ dáa kí o sì máa ní ìmọ̀lára rere!",
76
+ 5: "Ṣe ayẹyẹ, tàn ìdùnnú rẹ kaakiri, tẹ̀síwájú pẹ̀lú ìfẹ́!"}
77
+ }
78
+
79
+ # Map language codes to readable names
80
+ LANG_NAMES = {
81
+ 'en': 'English', 'fr': 'French', 'de': 'German', 'es': 'Spanish', 'it': 'Italian',
82
+ 'nl': 'Dutch', 'pt': 'Portuguese', 'ru': 'Russian', 'ar': 'Arabic', 'ja': 'Japanese',
83
+ 'yo': 'Yoruba'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  }
85
 
86
  def analyze_sentiment(text):
 
90
  sentiment = STAR_EMOJIS.get(stars, result["label"])
91
  confidence = f"{result['score']:.2f}"
92
 
93
+ # Language detection
94
  try:
95
  lang = detect(text)
96
  lang = 'yo' if lang == 'yo' else lang
 
99
  lang = 'en'
100
 
101
  action = ACTIONS[lang].get(stars, "")
102
+ lang_name = LANG_NAMES.get(lang, "Unknown")
103
+ return [[sentiment, confidence, action, lang_name]]
104
 
105
+ # Examples covering all 11 languages
106
  examples = [
107
  ["I absolutely love this new phone!"], # English
 
108
  ["Je déteste quand cette application plante."], # French
109
  ["Das Essen in diesem Restaurant war fantastisch!"], # German
110
  ["Este producto es muy malo."], # Spanish
111
+ ["Questo film è stato noioso e troppo lungo."], # Italian
112
+ ["De app werkt prima, maar kan beter."], # Dutch
113
+ ["Eu gostei muito do serviço, foi excelente!"], # Portuguese
114
+ ["Эта книга ужасна, я еле её дочитал."], # Russian
115
+ ["هذا الهاتف رائع للغاية، أنا سعيد جدًا به."], # Arabic
116
+ ["この映画は本当に面白かった!"], # Japanese
117
+ ["Mo nifẹ́ fíìmù yìí gan-an!"] # Yoruba
118
  ]
119
 
120
  # Gradio UI
 
122
  fn=analyze_sentiment,
123
  inputs=gr.Textbox(lines=3, placeholder="Type a sentence in any supported language..."),
124
  outputs=gr.Dataframe(
125
+ headers=["Emotion (1–5 Stars)", "Confidence", "What to do", "Language Detected"],
126
  row_count=1,
127
+ col_count=(4, "fixed"),
128
  ),
129
  examples=examples,
130
  title="🌍 Multilingual Emotion & Action Analyzer",
131
  description=(
132
+ "Supports 11 languages. Detects emotion (1–5 stars), provides suggested actions in the input language, "
133
+ "and shows which language was detected."
134
  ),
135
  )
136