cptcrk commited on
Commit
3af7af1
Β·
verified Β·
1 Parent(s): 3b72030

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -19
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import gradio as gr
2
  import matplotlib.pyplot as plt
3
  from transformers import pipeline
 
4
 
5
  # Laad de modellen
6
  translator = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
@@ -9,15 +10,21 @@ classifier = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-ba
9
  # Functie om meerdere zinnen te vertalen en analyseren
10
  def analyze_multilingual_sentences(text):
11
  if not text.strip():
12
- return "⚠️ Voer een tekst in voor analyse.", None
13
 
14
  # Splits de input op nieuwe regels (elke regel is een aparte zin)
15
  sentences = [s.strip() for s in text.split("\n") if s.strip()]
16
 
17
- # Vertaal elke zin naar Engels
18
- translated_sentences = [translator(sentence)[0]['translation_text'] for sentence in sentences]
19
 
20
- # Voer sentimentanalyse uit op elke vertaalde zin
 
 
 
 
 
 
21
  results = classifier(translated_sentences)
22
 
23
  # Tel het aantal positieve, negatieve en neutrale resultaten
@@ -26,7 +33,7 @@ def analyze_multilingual_sentences(text):
26
  neutral_count = len(results) - (positive_count + negative_count) # NEUTRAL
27
 
28
  # Maak een overzichtelijke output
29
- output = "**🌍 Meertalige Sentimentanalyse Resultaten:**\n\n"
30
  for original, translated, result in zip(sentences, translated_sentences, results):
31
  sentiment_label = result['label']
32
  score = result['score']
@@ -42,10 +49,13 @@ def analyze_multilingual_sentences(text):
42
  sentiment = "NEUTRAL"
43
  emoji = "🟦"
44
 
45
- output += f"πŸ“Œ **'{original}'**\nπŸ”„ **Vertaling:** {translated}\nπŸ“Š **Sentiment:** {emoji} {sentiment} ({score:.2f})\n\n"
 
 
 
46
 
47
  # Maak een grafiek met de sentimentverdeling
48
- labels = ["Positief", "Neutraal", "Negatief"]
49
  values = [positive_count, neutral_count, negative_count]
50
  colors = ["#4CAF50", "#2196F3", "#F44336"] # Groen, Blauw, Rood
51
 
@@ -55,8 +65,20 @@ def analyze_multilingual_sentences(text):
55
 
56
  return output, fig
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  # Gradio-interface met tekstanalyse en een grafiek
59
- # Aangepaste Gradio-interface met stijling
60
  demo = gr.Interface(
61
  fn=analyze_multilingual_sentences,
62
  inputs=gr.Textbox(
@@ -70,21 +92,15 @@ demo = gr.Interface(
70
  Enter sentences in any languageβ€”this AI-powered app translates, analyzes the vibe, and shows the results in a cool summary & chart.
71
  </div>
72
  """,
73
- examples=[
74
- ["I just aced my exam. My cat knocked over my coffee. Pineapple on pizza is the best debate of our generation."],
75
- ["Woke up feeling like the main character. Spilled my cereal and questioned my life choices. This app better not judge me."],
76
- ["Mondays should be illegal. I found a sock that’s been missing for six months. The WiFi went out, total meltdown mode."],
77
- ["Bought a plant, named it Kevin. Kevin is already dying. Send help and sunlight."],
78
- ["Coffee is my entire personality now. Just danced in the rain and felt like I was in a movie. AI, tell me if I’m emotionally stable."],
79
- ["I accidentally sent β€˜love you’ to my boss. Had ice cream for breakfast because why not. My dog just ignored me, rude."],
80
- ["I love coding. Syntax error. WHY IS THIS HAPPENING TO ME."],
81
- ],
82
  theme="default",
83
  allow_flagging="never"
84
  )
85
 
 
 
 
86
  # Start de app
87
  demo.launch()
88
-
89
-
90
 
 
1
  import gradio as gr
2
  import matplotlib.pyplot as plt
3
  from transformers import pipeline
4
+ import langdetect
5
 
6
  # Laad de modellen
7
  translator = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
 
10
  # Functie om meerdere zinnen te vertalen en analyseren
11
  def analyze_multilingual_sentences(text):
12
  if not text.strip():
13
+ return "⚠️ Enter some text to analyze.", None
14
 
15
  # Splits de input op nieuwe regels (elke regel is een aparte zin)
16
  sentences = [s.strip() for s in text.split("\n") if s.strip()]
17
 
18
+ # Detecteer de taal van de eerste zin als referentie (kan niet per zin)
19
+ detected_lang = langdetect.detect(sentences[0]) if sentences else "en"
20
 
21
+ # Vertaal alleen als de tekst NIET in het Engels is
22
+ if detected_lang != "en":
23
+ translated_sentences = [translator(sentence)[0]['translation_text'] for sentence in sentences]
24
+ else:
25
+ translated_sentences = sentences
26
+
27
+ # Voer sentimentanalyse uit op de (vertaalde) tekst
28
  results = classifier(translated_sentences)
29
 
30
  # Tel het aantal positieve, negatieve en neutrale resultaten
 
33
  neutral_count = len(results) - (positive_count + negative_count) # NEUTRAL
34
 
35
  # Maak een overzichtelijke output
36
+ output = "**🌍 Sentiment Analysis Results:**\n\n"
37
  for original, translated, result in zip(sentences, translated_sentences, results):
38
  sentiment_label = result['label']
39
  score = result['score']
 
49
  sentiment = "NEUTRAL"
50
  emoji = "🟦"
51
 
52
+ output += f"πŸ“Œ **'{original}'**\n"
53
+ if detected_lang != "en": # Alleen vertaling tonen als invoer niet in het Engels is
54
+ output += f"πŸ”„ **Translation:** {translated}\n"
55
+ output += f"πŸ“Š **Sentiment:** {emoji} {sentiment} ({score:.2f})\n\n"
56
 
57
  # Maak een grafiek met de sentimentverdeling
58
+ labels = ["Positive", "Neutral", "Negative"]
59
  values = [positive_count, neutral_count, negative_count]
60
  colors = ["#4CAF50", "#2196F3", "#F44336"] # Groen, Blauw, Rood
61
 
 
65
 
66
  return output, fig
67
 
68
+ # Voorbeelden gesplitst in boven en onder
69
+ examples_top = [
70
+ ["I just aced my exam. My cat knocked over my coffee. Pineapple on pizza is the best debate of our generation."],
71
+ ["Woke up feeling like the main character. Spilled my cereal and questioned my life choices. This app better not judge me."],
72
+ ["Mondays should be illegal. I found a sock that’s been missing for six months. The WiFi went out, total meltdown mode."]
73
+ ]
74
+
75
+ examples_bottom = [
76
+ ["Bought a plant, named it Kevin. Kevin is already dying. Send help and sunlight."],
77
+ ["Coffee is my entire personality now. Just danced in the rain and felt like I was in a movie. AI, tell me if I’m emotionally stable."],
78
+ ["I accidentally sent β€˜love you’ to my boss. Had ice cream for breakfast because why not. My dog just ignored me, rude."]
79
+ ]
80
+
81
  # Gradio-interface met tekstanalyse en een grafiek
 
82
  demo = gr.Interface(
83
  fn=analyze_multilingual_sentences,
84
  inputs=gr.Textbox(
 
92
  Enter sentences in any languageβ€”this AI-powered app translates, analyzes the vibe, and shows the results in a cool summary & chart.
93
  </div>
94
  """,
95
+ examples=examples_top, # Eerste drie voorbeelden boven
 
 
 
 
 
 
 
 
96
  theme="default",
97
  allow_flagging="never"
98
  )
99
 
100
+ # Extra voorbeeldsectie onder het invoerveld
101
+ extra_examples = gr.Examples(examples_bottom, inputs=demo.input_components)
102
+
103
  # Start de app
104
  demo.launch()
105
+ extra_examples.launch()
 
106