jr-95's picture
Update app.py
c289b72 verified
import gradio as gr
from transformers import pipeline
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import plotly.express as px
# Initialize sentiment analysis pipeline
sentiment_pipeline = pipeline("sentiment-analysis", model='distilbert-base-uncased-finetuned-sst-2-english')
def categorize_sentiment(score):
emoji_mapping = {
'Highly Dissatisfied': '😑',
'Dissatisfied': '😞',
'Neutral': '😐',
'Satisfied': '😊',
'Highly Satisfied': 'πŸ˜„'
}
if score >= 0.8:
return 'Highly Satisfied', emoji_mapping['Highly Satisfied']
elif score >= 0.1:
return 'Satisfied', emoji_mapping['Satisfied']
elif score >= -0.1:
return 'Neutral', emoji_mapping['Neutral']
elif score >= -0.8:
return 'Dissatisfied', emoji_mapping['Dissatisfied']
else:
return 'Highly Dissatisfied', emoji_mapping['Highly Dissatisfied']
def analyze_sentiment(input_text):
result = sentiment_pipeline(input_text)[0]
label = result['label']
score = result['score']
if label == "NEGATIVE":
score = -score # Make the score negative if the label is negative
emoji = "😊" if label == "POSITIVE" else "😞"
sentiment_label_with_emoji = f'{label} {emoji}'
sentiment_category, emoji = categorize_sentiment(score)
return str(score), sentiment_label_with_emoji, sentiment_category
def analyze_sentiments_from_excel(file):
try:
df = pd.read_excel(file.name)
except Exception as e:
return str(e), None, None, None, None # Return error message if file cannot be read
results = []
for text in df['Text']:
result = sentiment_pipeline(text)[0]
label = result['label']
score = result['score']
if label == "POSITIVE":
score = abs(score)
else:
score = -abs(score)
sentiment_label, emoji = categorize_sentiment(score)
results.append((text, score, label, sentiment_label, emoji))
results_df = pd.DataFrame(results, columns=['Text', 'Sentiment Score', 'Sentiment Label', 'Sentiment Category', 'Emoji'])
# Calculate percentages for each sentiment category
sentiment_counts = results_df['Sentiment Category'].value_counts(normalize=True) * 100
# Create pie chart for sentiment labels
fig_labels = px.pie(results_df, names='Sentiment Label', title='Sentiment Label Distribution')
# Create histogram for sentiment scores
fig_scores = px.histogram(results_df, x='Sentiment Score', title='Sentiment Score Distribution')
# Generate Word Cloud
text = " ".join(results_df['Text'].tolist())
wordcloud = WordCloud(width=800, height=400, random_state=21, max_font_size=110).generate(text)
plt.figure(figsize=(12, 8))
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis('off')
plt.title('Word Cloud')
plt.tight_layout()
wordcloud_fig = plt
return results_df, sentiment_counts, fig_labels, fig_scores, wordcloud_fig
def switch_app(app_name):
if app_name == "Sentiment Analysis":
iface1.show()
iface2.hide()
else:
iface1.hide()
iface2.show()
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
input_text = gr.Textbox(lines=5, label="Input Text", placeholder="Kindly type in your product review")
output_text = [
gr.Textbox(label="Sentiment Score"),
gr.Textbox(label="Sentiment Label"),
gr.HTML(label="Sentiment Category")
]
iface1 = gr.Interface(analyze_sentiment,
inputs=input_text,
outputs=output_text,
title='<span style="color: yellow">Sentiment Analysis</span>',
description='Explore the Emotions in Text. Experience the power of sentiment analysis with our tool. Get precise sentiment scores, emotive emojis, and categorized sentiments for any text.',
theme='dark',
css="""body {background-color: #121212; font-family: Arial, sans-serif;}
.gradio {box-shadow: none; border-radius: 10px;}
.input {background-color: #1E1E1E; color: #FFFFFF; border: none;}
.output {background-color: #1E1E1E; color: #FFFFFF; border: none;}
.output p {margin: 5px;}
.output div {margin: 5px;}
.output .highlight {padding: 5px; border-radius: 5px;}""")
with gr.Column():
file = gr.File(label="Upload Excel file")
output_text = [
gr.Dataframe(label="Text Analysis"),
gr.Textbox(label="Sentiment Category"),
gr.Plot(label="Sentiment Label"),
gr.Plot(label="Sentiment Score"),
gr.Plot(label="Word Cloud")
]
iface2 = gr.Interface(analyze_sentiments_from_excel,
inputs=file,
outputs=output_text,
title='<span style="color: yellow">Sentiment Analysis from Excel</span>',
description='Upload an Excel file with sentiment texts and predict sentiment scores and labels. Analyze the sentiment distribution.',
theme='dark',
css="""body {background-color: #121212; font-family: Arial, sans-serif;}
.gradio {box-shadow: none; border-radius: 10px;}
.input {background-color: #1E1E1E; color: #FFFFFF; border: none;}
.output {background-color: #1E1E1E; color: #FFFFFF; border: none;}
.output p {margin: 5px;}
.output div {margin: 5px;}
.output .highlight {padding: 5px; border-radius: 5px;}""")
with gr.Row():
switch_button = gr.Button("Switch App")
switch_button.click(switch_app, inputs=gr.Dropdown(["Sentiment Analysis", "Sentiment Analysis from Excel"], label="Select App"), outputs=None)
demo.launch()