Spaces:
Runtime error
Runtime error
File size: 5,530 Bytes
61f05ce b8aad66 61f05ce 3af7af1 61f05ce b8aad66 7d1ca07 b8aad66 61f05ce b8aad66 7d1ca07 df5bddb 7d1ca07 b8aad66 e54e9af 3af7af1 7d1ca07 3af7af1 b8aad66 7d1ca07 b8aad66 61f05ce 8452db2 e54e9af b8aad66 8452db2 b8aad66 8452db2 e54e9af b8aad66 8452db2 e54e9af b8aad66 8452db2 e54e9af b8aad66 e54e9af 3af7af1 e54e9af 8452db2 b8aad66 3af7af1 b8aad66 f37a83b b8aad66 e54e9af 3af7af1 ed16904 68d5086 df5bddb ed16904 3af7af1 e54e9af 544f3d5 df5bddb 3b72030 b91a4f0 df5bddb ed16904 b91a4f0 ed16904 df5bddb 544f3d5 ed16904 f37a83b df5bddb ed16904 df5bddb ed16904 b91a4f0 df5bddb 68d5086 ed16904 61f05ce 544f3d5 b91a4f0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
import gradio as gr
import matplotlib.pyplot as plt
from transformers import pipeline
import langdetect
# Laad de modellen
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
classifier = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment")
# Functie om meerdere zinnen te vertalen en analyseren
def analyze_multilingual_sentences(text):
if not text.strip():
return "<p style='color:red;'><b>β οΈ Enter some text to analyze.</b></p>", None
# Splits de input op nieuwe regels (elke regel is een aparte zin)
sentences = [s.strip() for s in text.split("\n") if s.strip()]
# Detecteer de taal van de eerste zin als referentie
detected_lang = langdetect.detect(sentences[0]) if sentences else "en"
# Vertaal alleen als de tekst NIET in het Engels is
if detected_lang != "en":
translated_sentences = [translator(sentence)[0]['translation_text'] for sentence in sentences]
else:
translated_sentences = sentences
# Voer sentimentanalyse uit op de (vertaalde) tekst
results = classifier(translated_sentences)
# Tel het aantal positieve, negatieve en neutrale resultaten
positive_count = sum(1 for r in results if r['label'] == "LABEL_2") # POSITIVE
negative_count = sum(1 for r in results if r['label'] == "LABEL_0") # NEGATIVE
neutral_count = len(results) - (positive_count + negative_count) # NEUTRAL
# Maak een overzichtelijke output met aangepaste teksten
output = "<h3>π Sentiment Analysis Results:</h3><br>"
for original, translated, result in zip(sentences, translated_sentences, results):
sentiment_label = result['label']
score = result['score']
# Aangepaste tekst per sentiment
if sentiment_label == "LABEL_2":
sentiment = "WOW! Couldn't feel better."
color = "green"
elif sentiment_label == "LABEL_0":
sentiment = "So sorry ... What could make you feel better?"
color = "red"
else:
sentiment = "Just neutral today."
color = "blue"
output += f"<p><b>π '{original}'</b></p>"
if detected_lang != "en": # Alleen vertaling tonen als invoer niet in het Engels is
output += f"<p>π <i>Translation:</i> {translated}</p>"
output += f"<p style='color: {color}; font-weight: bold;'>π {sentiment} ({score:.2f})</p><hr>"
# Maak een grafiek met de sentimentverdeling
labels = ["Positive", "Neutral", "Negative"]
values = [positive_count, neutral_count, negative_count]
colors = ["#FFA500", "#2196F3", "#F44336"] # Oranje, Blauw, Rood
fig, ax = plt.subplots()
ax.pie(values, labels=labels, autopct='%1.1f%%', startangle=90, colors=colors)
ax.axis("equal") # Gelijke assen voor een ronde taartdiagram
return output, fig
# Voorbeeldzinnen
example_sentences_top = [
"I just won the lottery!",
"My phone battery died in the middle of an important call.",
"This weather is so boring."
]
example_sentences_bottom = [
"I woke up at 5 AM and went for a run.",
"This is the worst movie I have ever seen.",
"Just got a puppy, and I'm in love!",
"The internet is so slow today.",
"I spilled coffee on my laptop, disaster!",
"I finally finished my project, time to celebrate!"
]
# Functie om een voorbeeldzin toe te voegen aan het invoerveld zonder te overschrijven
def add_example_text(current_text, example):
if current_text.strip():
return f"{current_text}\n{example}"
return example
# Gradio-interface met duidelijke instructies en styling
with gr.Blocks(css=".orange-btn {background-color: #FFA500 !important; color: black !important; font-weight: bold; font-size: 16px; padding: 10px 20px; border-radius: 8px; border: none; cursor: pointer;} .orange-btn:hover {background-color: #FF8C00 !important;}") as demo:
gr.Markdown(
"""
<div style='font-size: 18px; font-weight: bold; text-align: center; color: #333;'>
Enter sentences in any language, <b>one per line</b>.
This AI-powered app translates, analyzes the vibe, and shows the results in a cool summary & chart.
</div>
"""
)
input_box = gr.Textbox(
lines=5,
placeholder="Hey there! Drop some sentences (one per line) and get instant sentiment vibesβpositive, neutral, or negative...",
label="Enter your own sentences"
)
# Voorbeeldzinnen bovenaan (toevoegen aan invoerveld)
gr.Markdown("<h3>π‘ Or try these sentences:</h3>")
with gr.Row():
for example in example_sentences_top:
gr.Button(example).click(add_example_text, inputs=[input_box, gr.Textbox(value=example, visible=False)], outputs=input_box, queue=False)
# Oranje knop voor sentimentanalyse (correct toegepast)
analyze_button = gr.Button("Tell me how I feel", elem_classes="orange-btn")
output_box = gr.HTML(label="Results")
plot_box = gr.Plot(label="Sentiment Distribution")
analyze_button.click(analyze_multilingual_sentences, inputs=input_box, outputs=[output_box, plot_box])
# Voorbeeldzinnen onderaan (toevoegen aan invoerveld)
gr.Markdown("<h3>π‘ Or try more sentences:</h3>")
with gr.Row():
for example in example_sentences_bottom:
gr.Button(example).click(add_example_text, inputs=[input_box, gr.Textbox(value=example, visible=False)], outputs=input_box, queue=False)
# Start de app
demo.launch(share=True)
|