Spaces:
Sleeping
Sleeping
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() |