anabury commited on
Commit
4cb1fa5
·
verified ·
1 Parent(s): 35fd465

Update app.py

Browse files

Updated version

Files changed (1) hide show
  1. app.py +52 -54
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
- # Emotion labels
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 for multiple languages
21
  ACTIONS = {
22
  'en': {
23
- 1: "Take a break, reflect on the situation, or seek support.",
24
- 2: "Consider whats bothering you and try to address it calmly.",
25
- 3: "Maintain balance; you’re feeling neutral, continue as usual.",
26
  4: "Share your positive experience and stay motivated!",
27
- 5: "Celebrate and spread your joy; keep up the enthusiasm!"
28
  },
29
  'fr': {
30
- 1: "Faites une pause, réfléchissez à la situation ou demandez de l'aide.",
31
- 2: "Considérez ce qui vous dérange et essayez d'y remédier calmement.",
32
- 3: "Restez équilibré; vous vous sentez neutre, continuez comme d'habitude.",
33
  4: "Partagez votre expérience positive et restez motivé !",
34
- 5: "Célébrez et partagez votre joie ; continuez avec enthousiasme !"
35
  },
36
  'de': {
37
- 1: "Machen Sie eine Pause, reflektieren Sie die Situation oder suchen Sie Unterstützung.",
38
- 2: "Überlegen Sie, was Sie stört, und versuchen Sie, es ruhig zu lösen.",
39
- 3: "Halten Sie das Gleichgewicht; Sie fühlen sich neutral, machen Sie wie gewohnt weiter.",
40
  4: "Teilen Sie Ihre positive Erfahrung und bleiben Sie motiviert!",
41
- 5: "Feiern Sie und verbreiten Sie Ihre Freude; bleiben Sie begeistert!"
42
  },
43
  'es': {
44
- 1: "Tómate un descanso, reflexiona sobre la situación o busca apoyo.",
45
- 2: "Considera lo que te molesta y trata de abordarlo con calma.",
46
- 3: "Mantén el equilibrio; te sientes neutral, continúa como de costumbre.",
47
  4: "Comparte tu experiencia positiva y mantente motivado!",
48
- 5: "Celebra y comparte tu alegría; continúa con entusiasmo!"
49
  },
50
  'it': {
51
- 1: "Fai una pausa, rifletti sulla situazione o cerca supporto.",
52
- 2: "Considera cosa ti disturba e cerca di affrontarlo con calma.",
53
- 3: "Mantieni l'equilibrio; ti senti neutrale, continua come al solito.",
54
  4: "Condividi la tua esperienza positiva e rimani motivato!",
55
- 5: "Festeggia e diffondi la tua gioia; continua con entusiasmo!"
56
  },
57
  'nl': {
58
- 1: "Neem een pauze, denk na over de situatie of zoek ondersteuning.",
59
- 2: "Overweeg wat je stoort en probeer het rustig aan te pakken.",
60
- 3: "Behoud je balans; je voelt je neutraal, ga door zoals gewoonlijk.",
61
  4: "Deel je positieve ervaring en blijf gemotiveerd!",
62
- 5: "Vier en verspreid je vreugde; blijf enthousiast!"
63
  },
64
  'pt': {
65
- 1: "Faça uma pausa, reflita sobre a situação ou busque apoio.",
66
- 2: "Considere o que está incomodando e tente resolver calmamente.",
67
- 3: "Mantenha o equilíbrio; você se sente neutro, continue como de costume.",
68
  4: "Compartilhe sua experiência positiva e mantenha-se motivado!",
69
- 5: "Celebre e espalhe sua alegria; continue 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': { # Yoruba
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
- # Detect language
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, the camera is stunning!"], # English
121
- ["Mo nifẹ́ fíìmù yìí gan-an!"], # Yoruba Positive
122
- ["Mo bínú gan-an ìṣẹ̀lẹ̀ náà."], # Yoruba Negative
123
- ["Je déteste quand cette application plante sans cesse."], # French
124
- ["Das Essen in diesem Restaurant war fantastisch!"], # German
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 including English, French, German, Spanish, Italian, Dutch, "
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