Sristi222 commited on
Commit
0d9356b
·
verified ·
1 Parent(s): 0f12e5b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -0
app.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+
7
+
8
+ # Use a pipeline as a high-level helper
9
+ from transformers import pipeline
10
+
11
+ # model_path = ("../Models/models--distilbert--distilbert-base-uncased-finetuned-sst-2-english/snapshots/714eb0fa89d2f80546fda750413ed43d93601a13")
12
+ # analyzer = pipeline("text-classification", model=model_path)
13
+
14
+ analyzer = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
15
+
16
+ # print(analyzer(["This is good", "This product is quite expensive"]))
17
+
18
+ def sentiment_analyzer(review):
19
+ sentiment = analyzer(review)
20
+ return sentiment[0]['label'], sentiment[0]['score'] # Return sentiment label and confidence score
21
+
22
+ def create_sentiment_pie_chart(df):
23
+ sentiment_counts = df['Sentiment'].value_counts()
24
+
25
+ # Style the pie chart
26
+ colors = ['#e67e22', '#3498db'] # Green for Positive, Red for Negative
27
+ explode = [0.05, 0] # Slightly separate the positive slice for emphasis
28
+
29
+ fig, ax = plt.subplots(figsize=(6, 6))
30
+ sentiment_counts.plot(
31
+ kind='pie',
32
+ colors=colors,
33
+ autopct='%1.1f%%',
34
+ startangle=140,
35
+ explode=explode,
36
+ ax=ax,
37
+ textprops={'fontsize': 10, 'color': 'black'},
38
+ radius=0.7 # Decrease radius to make the pie smaller
39
+ )
40
+ ax.set_title("Sentiment Distribution (Pie Chart)", fontsize=10, fontweight='bold', color='#34495e')
41
+ ax.set_ylabel("") # Remove default 'Count' label
42
+ plt.tight_layout()
43
+
44
+ return fig
45
+
46
+ # Create a styled bar chart
47
+ def create_sentiment_bar_chart(df):
48
+ sentiment_counts = df['Sentiment'].value_counts()
49
+
50
+ # Use Seaborn for stylish bar plots
51
+ fig, ax = plt.subplots(figsize=(8, 5))
52
+ # Use a categorical variable for hue to avoid the warning
53
+ sns.barplot(
54
+ x=sentiment_counts.index,
55
+ y=sentiment_counts.values,
56
+ # for hue warning which doesn't effect code
57
+ hue=sentiment_counts.index, # Use 'Sentiment' as the hue variable
58
+ palette=['#e67e22', '#3498db'], # Green for Positive, Red for Negative
59
+ ax=ax,
60
+ legend=False, # We don't need a legend for this plot
61
+ width = 0.5
62
+ )
63
+
64
+ # Add value annotations on top of each bar
65
+ for idx, value in enumerate(sentiment_counts.values):
66
+ ax.text(idx, value + 0.5, str(value), ha='center', fontsize=10, color='black', fontweight='bold')
67
+
68
+ ax.set_title("Sentiment Distribution (Bar Chart)", fontsize=12, fontweight='bold', color='#34495e')
69
+ ax.set_xlabel("Sentiment", fontsize=10, fontweight='bold', color='#34495e')
70
+ ax.set_ylabel("Count", fontsize=10, fontweight='bold', color='#34495e')
71
+ ax.spines['top'].set_visible(False) # Clean up borders
72
+ ax.spines['right'].set_visible(False)
73
+
74
+ plt.xticks(fontsize=10, fontweight='bold', color='#34495e')
75
+ plt.yticks(fontsize=10, color='#34495e')
76
+ plt.tight_layout()
77
+
78
+ return fig
79
+
80
+
81
+ # Define the main function to process the Excel file
82
+ def read_reviews_and_analyze_sentiment(file_object):
83
+ # Read the Excel file into a DataFrame
84
+ df = pd.read_excel(file_object)
85
+
86
+ # Ensure the column containing reviews exists
87
+ if 'Reviews' not in df.columns:
88
+ raise ValueError("The Excel file must contain a column named 'Reviews'.")
89
+
90
+ # Apply the sentiment analyzer and split into two columns
91
+ df[['Sentiment', 'Confidence']] = df['Reviews'].apply(
92
+ lambda x: pd.Series(sentiment_analyzer(x))
93
+ )
94
+
95
+ # Generate the pie and bar charts
96
+ pie_chart = create_sentiment_pie_chart(df)
97
+ bar_chart = create_sentiment_bar_chart(df)
98
+
99
+ return df, pie_chart, bar_chart
100
+
101
+
102
+
103
+ # Example usage:
104
+ # df = process_reviews("reviews.xlsx")
105
+ # print(df)
106
+
107
+ # result = read_reviews_and_analyze_sentiment("../Files/Updated_Reviews_Sample.xlsx")
108
+ # print(result)
109
+
110
+ import gradio as gr
111
+
112
+ # Custom CSS for styling the title
113
+ custom_css = """
114
+ .title { font-size: 24px; font-weight: bold; color: #34495e; }
115
+ .gradio-label, .gradio-description {
116
+ font-size: 18px; /* Increase font size */
117
+ font-weight: bold; /* Make text bold */
118
+ }
119
+ """
120
+
121
+ # Interface
122
+ interface = gr.Interface(
123
+ fn=read_reviews_and_analyze_sentiment,
124
+ inputs=gr.File(file_types=[".xlsx"], label="Upload Excel File"), # Accept only Excel files
125
+ outputs=[
126
+ gr.Dataframe(
127
+ headers=["Reviews", "Sentiment", "Confidence"], # Custom headers for output
128
+ label="Sentiment Analysis Results"
129
+ ),
130
+ gr.Plot(label="Sentiment Distribution (Pie Chart)"),
131
+ gr.Plot(label="Sentiment Distribution (Bar Chart)")
132
+ ],
133
+ title="Sentiment Analyzer with Confidence Scores",
134
+ description=(
135
+ "Upload an Excel file with a 'Reviews' column to analyze sentiments and "
136
+ "visualize the distribution in both pie and bar charts."
137
+ ),
138
+ theme="default", # Align components vertically
139
+ css=custom_css # Apply the custom CSS
140
+ )
141
+
142
+ interface.launch()
143
+