File size: 4,316 Bytes
aad2b5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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()