Spaces:
Runtime error
Runtime error
File size: 6,470 Bytes
6cfdc8d 1d59687 6cfdc8d 1d59687 6cfdc8d 1d59687 6cfdc8d c289b72 6cfdc8d c289b72 1d59687 6cfdc8d 1d59687 6cfdc8d 1d59687 |
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 140 141 142 143 144 145 146 147 148 |
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() |