Spaces:
Runtime error
Runtime error
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) | |