anabury commited on
Commit
91f79af
·
verified ·
1 Parent(s): d33ff5b

Update app.py

Browse files

Updated version

Files changed (1) hide show
  1. app.py +42 -22
app.py CHANGED
@@ -1,12 +1,16 @@
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
 
 
3
 
4
- # Multilingual model (10+ languages)
5
  MODEL = "nlptown/bert-base-multilingual-uncased-sentiment"
6
  tokenizer = AutoTokenizer.from_pretrained(MODEL)
7
  model = AutoModelForSequenceClassification.from_pretrained(MODEL)
8
  sentiment_model = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
9
 
 
 
10
  # Map stars (1–5) to emotion labels with emojis
11
  STAR_EMOJIS = {
12
  1: "😡 Very Negative",
@@ -16,46 +20,62 @@ STAR_EMOJIS = {
16
  5: "🤩 Very Positive"
17
  }
18
 
 
 
 
 
 
 
 
 
 
19
  def analyze_sentiment(text):
 
20
  result = sentiment_model(text)[0]
21
- stars = int(result["label"][0]) # "1 star" → 1
22
  sentiment = STAR_EMOJIS.get(stars, result["label"])
23
  confidence = f"{result['score']:.2f}"
24
- return [[sentiment, confidence]]
25
 
26
- # Example texts in different languages including Yoruba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  examples = [
28
  ["I absolutely love this new phone, the camera is stunning!"], # English
29
- ["Je déteste quand cette application plante sans cesse."], # French
30
- ["Das Essen in diesem Restaurant war fantastisch!"], # German
31
- ["Este producto es muy malo y no funciona."], # Spanish
32
- ["Questo film è stato noioso e troppo lungo."], # Italian
33
- ["Eu gostei muito do serviço, foi excelente!"], # Portuguese
34
- ["Эта книга ужасна, я еле её дочитал."], # Russian
35
- ["هذا الهاتف رائع للغاية، أنا سعيد جدًا به."], # Arabic
36
- ["この映画は本当に面白かった!"], # Japanese
37
- ["De app werkt prima, maar kan beter."], # Dutch
38
  ["Mo nifẹ́ fíìmù yìí gan-an!"], # Yoruba Positive
39
- ["Mo kọ́ láti rí ìrírí tó dáa nínú iṣẹ́ yìí."], # Yoruba Neutral
40
  ["Mo bínú gan-an sí ìṣẹ̀lẹ̀ náà."], # Yoruba Negative
 
41
  ]
42
 
43
  # Gradio UI
44
  demo = gr.Interface(
45
  fn=analyze_sentiment,
46
- inputs=gr.Textbox(lines=3, placeholder="Type a sentence here in one of 11+ languages..."),
47
  outputs=gr.Dataframe(
48
- headers=["Emotion (1–5 Stars)", "Confidence"],
49
  row_count=1,
50
- col_count=(2, "fixed"),
51
  ),
52
  examples=examples,
53
- title="🌍 Multilingual Emotion & Sentiment Analyzer",
54
  description=(
55
- "Supports 11+ languages (English, French, German, Spanish, Italian, Dutch, "
56
- "Portuguese, Russian, Arabic, Japanese, Yoruba). Detects fine-grained emotions "
57
- "with 5 levels:\n\n"
58
- "😡 Very Negative | ☹️ Negative | 😐 Neutral | 🙂 Positive | 🤩 Very Positive"
59
  ),
60
  )
61
 
 
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",
 
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"])
37
  confidence = f"{result['score']:.2f}"
 
38
 
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
66
  demo = gr.Interface(
67
  fn=analyze_sentiment,
68
+ inputs=gr.Textbox(lines=3, placeholder="Type a sentence in any supported language..."),
69
  outputs=gr.Dataframe(
70
+ headers=["Emotion (1–5 Stars)", "Confidence", "What to do"],
71
  row_count=1,
72
+ col_count=(3, "fixed"),
73
  ),
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