File size: 5,561 Bytes
0113101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
130
131
132
133
134
135
136
137
138
139
from textblob import TextBlob
import gradio as gr
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

def final_sentiment_app(text):
    if not text.strip():
        return "⚠️ Please enter some text!", None

    sentences = [s.strip() for s in text.replace('!','!|').replace('?','?|').replace('.','.|').split('|') if s.strip()]

    if len(sentences) == 0:
        return "⚠️ No sentences found!", None

    scores = []
    colors = []
    sentence_results = []
    pos_count = neg_count = neu_count = 0
    total_score = 0

    for i, sentence in enumerate(sentences):
        blob = TextBlob(sentence)
        score = round(blob.sentiment.polarity, 2)
        subjectivity = round(blob.sentiment.subjectivity, 2)
        scores.append(score)
        total_score += score

        if score >= 0.5:
            label = "🀩 Very Positive"
            colors.append('#00e676')
            pos_count += 1
        elif score > 0.1:
            label = "😊 Positive"
            colors.append('#00c853')
            pos_count += 1
        elif score <= -0.5:
            label = "😑 Very Negative"
            colors.append('#ff1744')
            neg_count += 1
        elif score < -0.1:
            label = "😞 Negative"
            colors.append('#d50000')
            neg_count += 1
        else:
            label = "😐 Neutral"
            colors.append('#aa00ff')
            neu_count += 1

        sentence_results.append(
            f"S{i+1} {label} | Score: {score} | Subjectivity: {subjectivity}\n"
            f"    β†’ \"{sentence}\""
        )

    avg = round(total_score / len(sentences), 2)

    if avg >= 0.5:    overall = "🀩 Very Positive"
    elif avg > 0.1:   overall = "😊 Positive"
    elif avg <= -0.5: overall = "😑 Very Negative"
    elif avg < -0.1:  overall = "😞 Negative"
    else:             overall = "😐 Neutral"

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
    fig.patch.set_facecolor('#0d0d1a')
    fig.suptitle('Sentiment Analysis Report', color='white', fontsize=14, fontweight='bold')

    ax1.set_facecolor('#1a1a2e')
    x = range(len(sentences))
    bars = ax1.bar(x, scores, color=colors, edgecolor='white', linewidth=0.5, width=0.5)
    ax1.axhline(y=0, color='white', linewidth=1, linestyle='--', alpha=0.5)
    ax1.set_title('Score Per Sentence', color='white', fontsize=11)
    ax1.set_xticks(x)
    ax1.set_xticklabels([f'S{i+1}' for i in x], color='white')
    ax1.set_ylabel('Polarity (-1 to +1)', color='white')
    ax1.set_ylim(-1.2, 1.2)
    ax1.tick_params(colors='white')
    for bar, score in zip(bars, scores):
        ypos = bar.get_height()+0.05 if score >= 0 else bar.get_height()-0.12
        ax1.text(bar.get_x()+bar.get_width()/2, ypos,
                str(score), ha='center', color='white', fontsize=9, fontweight='bold')

    ax2.set_facecolor('#1a1a2e')
    pie_data = [(pos_count,'Positive\n','#00c853'),
                (neg_count,'Negative\n','#ff1744'),
                (neu_count,'Neutral\n','#aa00ff')]
    pie_data = [(v,l,c) for v,l,c in pie_data if v > 0]
    ax2.pie(
        [d[0] for d in pie_data],
        labels=[f"{d[1]}({d[0]})" for d in pie_data],
        colors=[d[2] for d in pie_data],
        autopct='%1.0f%%',
        textprops={'color':'white','fontsize':10},
        wedgeprops={'edgecolor':'white','linewidth':1.2},
        startangle=90
    )
    ax2.set_title('Sentiment Distribution', color='white', fontsize=11)
    plt.tight_layout()

    report = "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
    report += "πŸ“‹ SENTENCE BREAKDOWN\n"
    report += "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
    report += "\n".join(sentence_results)
    report += "\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
    report += "πŸ“Š FINAL SUMMARY\n"
    report += "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
    report += f"🎯 Overall Sentiment  : {overall}\n"
    report += f"πŸ“ˆ Average Score      : {avg}\n"
    report += f"βœ… Positive sentences : {pos_count}\n"
    report += f"❌ Negative sentences : {neg_count}\n"
    report += f"βž– Neutral sentences  : {neu_count}\n"
    report += f"πŸ“ Total sentences    : {len(sentences)}\n"
    report += f"πŸ“ Total words        : {len(text.split())}\n"
    report += "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

    return report, fig

app = gr.Interface(
    fn=final_sentiment_app,
    inputs=gr.Textbox(
        placeholder="Paste a paragraph, product review, tweet or any text...",
        label="πŸ“ Enter Your Text",
        lines=6
    ),
    outputs=[
        gr.Textbox(label="πŸ“‹ Analysis Report", lines=18),
        gr.Plot(label="πŸ“ˆ Visual Charts")
    ],
    title="🧠 Sentiment Analyzer Pro",
    description="✨ AI-powered sentiment detection | Sentence-by-sentence breakdown | Visual charts | Built with Python & NLP",
    examples=[
        ["I love this college! The canteen food is terrible. Classes are okay. Teachers are amazing!"],
        ["This phone is fantastic! Battery life is poor. Camera quality is outstanding. Delivery was late."],
        ["I am so happy today! Work was stressful. But my friends made it better. Overall a good day!"],
        ["The movie was boring. Acting was terrible. But the music was absolutely amazing!"]
    ],
    theme="soft"
)

app.launch()