Spaces:
Sleeping
Sleeping
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 | |
import io | |
from pathlib import Path | |
import tempfile | |
# 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): | |
df = pd.read_excel(file.name) | |
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 | |
# Convert DataFrame to CSV | |
csv_buffer = io.StringIO() | |
results_df.to_csv(csv_buffer, index=False) | |
csv_bytes = csv_buffer.getvalue().encode() | |
# Create a temporary file for the CSV data | |
with tempfile.NamedTemporaryFile(delete=False, suffix='.csv') as temp_file: | |
temp_file.write(csv_bytes) | |
temp_file_path = str(Path(temp_file.name)) # Convert Path to string | |
# Create a new gr.File instance with the temporary file path | |
csv_download = gr.File(value=temp_file_path, label='Download CSV', file_count=1) | |
return results_df, sentiment_counts, fig_labels, fig_scores, wordcloud_fig, csv_download | |
def switch_app(app_name): | |
if app_name == "Sentiment Analysis": | |
iface1.show() | |
iface2.hide() | |
else: | |
iface1.hide() | |
iface2.show() | |
welcome_text = """ | |
<div style="background-color: #f0f0f0; padding: 20px; border-radius: 10px;"> | |
<h1 style="color: #333333; text-align: center;">Welcome to the Sentiment Analysis App</h1> | |
<p style="color: #555555; text-align: center; font-size: 1.2em;">This app allows you to analyze the sentiment of text, either by entering it directly or by uploading an Excel file.</p> | |
<p style="color: #777777; text-align: center; font-size: 1.1em;">Choose the desired option from the tabs above to get started!</p> | |
<p style="color: #ff5733; text-align: center; font-size: 1.5em; font-weight: bold;">Get ready to explore the emotions in text!</p> | |
</div> | |
""" | |
welcome_interface = gr.Interface( | |
fn=None, # No function needed for the welcome message | |
inputs=None, | |
outputs=gr.HTML(welcome_text), | |
title="Welcome", | |
theme="huggingface" | |
) | |
iface1 = gr.Interface(analyze_sentiment, | |
inputs=gr.Textbox(lines=5, label="Input Text", placeholder="Kindly type in your product review"), | |
outputs=[ | |
gr.Textbox(label="Sentiment Score"), | |
gr.Textbox(label="Sentiment Label"), | |
gr.HTML(label="Sentiment Category") | |
], | |
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;}""") | |
iface2 = gr.Interface(analyze_sentiments_from_excel, | |
inputs=gr.File(label="Upload Excel file"), | |
outputs=[ | |
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"), | |
gr.File(label="Download CSV") | |
], | |
title='<span style="color: #32CD32">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;}""") | |
#app | |
demo = gr.TabbedInterface([welcome_interface, iface1, iface2], ["Welcome", "Single Sentiment Analysis", "Bulk Sentiment Analysis"], theme="huggingface") | |
demo.launch() |