anabury commited on
Commit
35fd465
·
verified ·
1 Parent(s): 2a9cd2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -27
app.py CHANGED
@@ -1,17 +1,14 @@
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
3
  from langdetect import detect
4
- from googletrans import Translator
5
 
6
- # Multilingual sentiment model
7
  MODEL = "nlptown/bert-base-multilingual-uncased-sentiment"
8
  tokenizer = AutoTokenizer.from_pretrained(MODEL)
9
  model = AutoModelForSequenceClassification.from_pretrained(MODEL)
10
  sentiment_model = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
11
 
12
- translator = Translator()
13
-
14
- # Map stars (1–5) to emotion labels with emojis
15
  STAR_EMOJIS = {
16
  1: "😡 Very Negative",
17
  2: "☹️ Negative",
@@ -20,17 +17,89 @@ STAR_EMOJIS = {
20
  5: "🤩 Very Positive"
21
  }
22
 
23
- # Suggested actions in English
24
  ACTIONS = {
25
- 1: "Take a break, reflect on the situation, or seek support.",
26
- 2: "Consider what’s bothering you and try to address it calmly.",
27
- 3: "Maintain balance; you’re feeling neutral, continue as usual.",
28
- 4: "Share your positive experience and stay motivated!",
29
- 5: "Celebrate and spread your joy; keep up the enthusiasm!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  }
31
 
32
  def analyze_sentiment(text):
33
- # Sentiment analysis
34
  result = sentiment_model(text)[0]
35
  stars = int(result["label"][0])
36
  sentiment = STAR_EMOJIS.get(stars, result["label"])
@@ -39,27 +108,21 @@ def analyze_sentiment(text):
39
  # Detect language
40
  try:
41
  lang = detect(text)
 
42
  except:
43
- lang = "en"
44
-
45
- # Translate action to detected language
46
- action_en = ACTIONS.get(stars, "")
47
- if lang != "en":
48
- try:
49
- action_translated = translator.translate(action_en, dest=lang).text
50
- except:
51
- action_translated = action_en
52
- else:
53
- action_translated = action_en
54
 
55
- return [[sentiment, confidence, action_translated]]
 
56
 
57
- # Example texts including Yoruba
58
  examples = [
59
  ["I absolutely love this new phone, the camera is stunning!"], # English
60
  ["Mo nifẹ́ fíìmù yìí gan-an!"], # Yoruba Positive
61
  ["Mo bínú gan-an sí ìṣẹ̀lẹ̀ náà."], # Yoruba Negative
62
  ["Je déteste quand cette application plante sans cesse."], # French
 
 
63
  ]
64
 
65
  # Gradio UI
@@ -74,8 +137,9 @@ demo = gr.Interface(
74
  examples=examples,
75
  title="🌍 Multilingual Emotion & Action Analyzer",
76
  description=(
77
- "Supports multiple languages including English, Yoruba, French, German, Spanish, etc. "
78
- "Detects emotion (1–5 stars) and provides suggested actions in the same language as input."
 
79
  ),
80
  )
81
 
 
1
  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
  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 what’s 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à.",
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):
102
+ # Sentiment
103
  result = sentiment_model(text)[0]
104
  stars = int(result["label"][0])
105
  sentiment = STAR_EMOJIS.get(stars, result["label"])
 
108
  # Detect language
109
  try:
110
  lang = detect(text)
111
+ lang = lang if lang in ACTIONS else 'en'
112
  except:
113
+ lang = 'en'
 
 
 
 
 
 
 
 
 
 
114
 
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 sí ìṣẹ̀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
  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