Aeon-Avinash commited on
Commit
212b7d0
·
verified ·
1 Parent(s): d86f2c2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+ import torch
3
+ import gradio as gr
4
+
5
+
6
+ def sentiment_analysis(text):
7
+ analyzer = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
8
+ sentiment = analyzer(text)
9
+ return [sentiment[0]['label'], sentiment[0]['score']]
10
+
11
+ # Test 1:
12
+ # print(analyzer(["This is awesome. Reliable product.", "Very expensive product. Company should use better pricing."]))
13
+ # print(sentiment_analysis(["This is awesome. Reliable product.", "Very expensive product. Company should use better pricing."]))
14
+ # [{'label': 'POSITIVE', 'score': 0.9998791217803955}, {'label': 'NEGATIVE', 'score': 0.9994811415672302}]
15
+
16
+ # Test with Gradio:
17
+
18
+ # gr.close_all()
19
+
20
+ # version 0.1
21
+ # demo = gr.Interface(
22
+ # fn=sentiment_analysis,
23
+ # inputs=[gr.Textbox(label="Text Input for Sentiment Analysis", lines=4)],
24
+ # outputs=[gr.Textbox(label="Analyzed Sentiment", lines=4), gr.Textbox(label="Sentiment Strength", lines=1)],
25
+ # title="GenAI Sentiment Analyzer",
26
+ # description="This App does seniment analysis of text input")
27
+ # demo.launch()
28
+
29
+ # Uploading an excel file and getting output as required:
30
+ import pandas as pd
31
+ import matplotlib.pyplot as plt
32
+
33
+ def create_charts(df):
34
+ # Validate DataFrame
35
+ if not all(col in df.columns for col in ['Review', 'Sentiment', 'Sentiment Score']):
36
+ raise ValueError("The DataFrame must contain 'Review', 'Sentiment', and 'Sentiment Score' columns.")
37
+ # Create Pie Chart for Sentiment Distribution
38
+ sentiment_counts = df['Sentiment'].value_counts()
39
+ fig1, ax1 = plt.subplots(figsize=(8, 6))
40
+ ax1.pie(sentiment_counts, labels=sentiment_counts.index, autopct='%1.1f%%', colors=['skyblue', 'lightcoral'])
41
+ ax1.set_title('Distribution of Positive and Negative Reviews')
42
+
43
+ # Create Scatter Plot for Sentiment Scores
44
+ fig2, ax2 = plt.subplots(figsize=(10, 6))
45
+ for sentiment, color in zip(['positive', 'negative'], ['green', 'red']):
46
+ subset = df[df['Sentiment'].str.lower() == sentiment]
47
+ ax2.scatter(subset.index, subset['Sentiment Score'], label=sentiment.capitalize(), color=color, alpha=0.6)
48
+
49
+ ax2.axhline(0, color='gray', linewidth=0.5)
50
+ ax2.set_xlabel('Review Index')
51
+ ax2.set_ylabel('Sentiment Score')
52
+ ax2.set_title('Scatter Plot of Reviews by Sentiment Score')
53
+ ax2.legend()
54
+
55
+ return fig1, fig2
56
+
57
+
58
+
59
+ def analyze_reviews(file_path):
60
+ # Read the Excel file
61
+ df = pd.read_excel(file_path)
62
+
63
+ # Attempt to identify the review column if it is not labeled correctly
64
+ if 'Review' not in df.columns:
65
+ for col in df.columns:
66
+ if df[col].dtype == 'object': # Assuming reviews are text
67
+ df.rename(columns={col: 'Review'}, inplace=True)
68
+ break
69
+
70
+ # Ensure the dataframe now has a 'Review' column
71
+ if 'Review' not in df.columns:
72
+ raise ValueError("The input file must contain a column with review text.")
73
+
74
+ # Remove any column that contains serial numbers
75
+ df = df[[col for col in df.columns if not pd.api.types.is_numeric_dtype(df[col]) or col == 'Review']]
76
+
77
+
78
+ # Apply the get_sentiment function to each review
79
+ results = df['Review'].apply(sentiment_analysis)
80
+
81
+ # Split the results into separate columns for sentiment and sentiment score
82
+ [df['Sentiment'], df['Sentiment Score']] = zip(*results)
83
+
84
+ # Adjust the sentiment score to be negative if the sentiment is negative
85
+ df.loc[df['Sentiment'] == 'NEGATIVE', 'Sentiment Score'] *= -1
86
+
87
+ pie_chart, scatter_plot = create_charts(df)
88
+
89
+ return [df, pie_chart, scatter_plot]
90
+
91
+
92
+ # Example usage
93
+ # file_path = '/teamspace/studios/this_studio/sentiment-analyzer/Sample_Sentiments (1).xlsx'
94
+ # result_df = analyze_reviews(file_path)
95
+ # print(result_df)
96
+
97
+
98
+
99
+
100
+ gr.close_all()
101
+
102
+ # version 0.2
103
+ demo = gr.Interface(
104
+ fn=analyze_reviews,
105
+ inputs=[gr.File(label="Upload your excel file containing user reviews")],
106
+ outputs=[
107
+ gr.DataFrame(label="Analysis of the uploaded excel file"),
108
+ gr.Plot(label="Sentiment Analysis - Positive & Negative"),
109
+ gr.Plot(label="Sentiment Analysis - Sentiment Score Distribution")
110
+ ],
111
+ title="GenAI Sentiment Analyzer",
112
+ description="This App does sentiment analysis of User Reviews")
113
+ demo.launch()
114
+
115
+