# pylint: disable=import-error import gradio as gr import numpy as np import matplotlib.pyplot as plt from transformers import pipeline # Load pre-trained sentiment analysis model sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english") def analyze_sentiment(text): """ Analyze the sentiment of input text """ if not text or not text.strip(): return { "Sentiment": "N/A", "Confidence": 0, "Positive": 0, "Negative": 0 } result = sentiment_analyzer(text)[0] sentiment = result["label"] confidence = result["score"] # Create result dictionary output = { "Sentiment": "Positive" if sentiment == "POSITIVE" else "Negative", "Confidence": round(confidence * 100, 2) } # Add values for the gauge chart output["Positive"] = confidence if sentiment == "POSITIVE" else 1 - confidence output["Negative"] = 1 - output["Positive"] return output def process_text(text): """ Process the text and create visualizations """ result = analyze_sentiment(text) # Create a visual representation of the sentiment labels = ['Positive', 'Negative'] sizes = [result["Positive"], result["Negative"]] colors = ['#4CAF50', '#F44336'] fig, ax = plt.subplots(figsize=(5, 3)) ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90) ax.axis('equal') plt.title('Sentiment Analysis') return result["Sentiment"], result["Confidence"], fig # Define examples for users to try examples = [ ["I love this product! It's absolutely fantastic and exceeded all my expectations."], ["This was a terrible experience. I will never use this service again."], ["The quality is okay, but the price is a bit high for what you get."], ["I've had better, but I've also had much worse. It's a decent option."], ["This is the best decision I've ever made. Highly recommended!"] ] # Create Gradio interface with gr.Blocks(title="Sentiment Analyzer", theme=gr.themes.Soft()) as demo: gr.Markdown( """ # 💬 Text Sentiment Analyzer This interactive tool analyzes the sentiment of any text, determining whether it's positive or negative. It's particularly useful for analyzing customer feedback, social media comments, or product reviews. Try typing or pasting text in the input area below, or select one of the examples to see how it works! """ ) with gr.Row(): with gr.Column(scale=3): text_input = gr.Textbox( label="Enter text to analyze", placeholder="Type or paste text here...", lines=5 ) analyze_btn = gr.Button("Analyze Sentiment", variant="primary") with gr.Column(scale=2): sentiment_label = gr.Label(label="Result") confidence = gr.Number(label="Confidence Score (%)") sentiment_gauge = gr.Plot(label="Sentiment Distribution") # Add examples section gr.Examples( examples=examples, inputs=text_input, outputs=[sentiment_label, confidence, sentiment_gauge], fn=process_text, cache_examples=True ) # Set up the click event analyze_btn.click( fn=process_text, inputs=text_input, outputs=[sentiment_label, confidence, sentiment_gauge] ) gr.Markdown(""" ### How it works This tool uses a DistilBERT model fine-tuned for sentiment analysis. The model has been trained on a large dataset of text with positive and negative sentiments, allowing it to recognize emotional tone in written text. ### Applications - **Customer Service**: Monitor customer feedback in real-time - **Market Research**: Analyze opinions about products or services - **Social Media Monitoring**: Track sentiment about your brand across platforms - **Content Analysis**: Evaluate the emotional impact of your content Created by [Vinicius Guerra e Ribas](https://viniciusgribas.netlify.app/) """) # Launch the app if __name__ == "__main__": demo.launch()