neena2024 commited on
Commit
b68e731
·
verified ·
1 Parent(s): a3d0f2a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -52
app.py CHANGED
@@ -1,65 +1,75 @@
1
- import gradio as gr
2
  import torch
 
3
  import pandas as pd
 
4
 
5
  # Use a pipeline as a high-level helper
6
  from transformers import pipeline
7
- analyzer = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- # Load model directly
10
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
11
 
12
- def sentiment_analyzer(reviews):
13
- sentiment = analyzer(reviews)
14
- return sentiment
15
 
16
- # Read Reviews & Analyzer Sentiments
17
  def read_reviews_and_analyze_sentiment(file_object):
18
- """
19
- Reads reviews from an Excel file, analyzes their sentiment, and returns a DataFrame
20
- with the reviews, sentiment, and sentiment score.
21
-
22
- Parameters:
23
- input_excel (str): Path to the input Excel file.
24
-
25
- Returns:
26
- pd.DataFrame: DataFrame containing reviews, sentiment, and sentiment score.
27
- """
28
- # Read the Excel file
29
- df = pd.read_xlsx(file_object)
30
-
31
-
32
- # Check if 'reviews' column exists
33
- if 'review' not in df.columns:
34
- raise ValueError("The input Excel file must contain a column named 'reviews'.")
35
-
36
- # Analyze sentiment for each review
37
- sentiments = []
38
- scores = []
39
- for review in df['review']:
40
- obj = sentiment_analyzer(review[0])
41
- sentiment = obj[0]['label']
42
- score = obj[0]['score']
43
- sentiments.append(sentiment)
44
- scores.append(score)
45
-
46
- # Add sentiment and score to the DataFrame
47
- df['sentiment'] = sentiments
48
- df['sentiment_score'] = scores
49
-
50
- return df
51
-
52
- # file_path = '/content/sample_data/amazon customer reviews.csv'
53
- # result = read_reviews_and_analyze_sentiment(file_path)
54
- # print(result)
55
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- gr.close_all()
58
 
59
  demo = gr.Interface(fn=read_reviews_and_analyze_sentiment,
60
- inputs=[gr.File(file_types=['xlsx'], label="Upload review file")],
61
- outputs=[gr.Dataframe(label="Analyze the sentiment of the reviews")],
62
- title = "Gen AI Sentiment Analyzer",
63
- description= "Review is positive negative."
64
- )
65
- demo.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
1
  import torch
2
+ import gradio as gr
3
  import pandas as pd
4
+ import matplotlib.pyplot as plt
5
 
6
  # Use a pipeline as a high-level helper
7
  from transformers import pipeline
8
+ # model_path = ("../Models/models--distilbert--distilbert-base-uncased-finetuned-sst-2-english"
9
+ # "/snapshots/714eb0fa89d2f80546fda750413ed43d93601a13")
10
+
11
+ analyzer = pipeline("text-classification",
12
+ model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
13
+
14
+ # analyzer = pipeline("text-classification",
15
+ # model=model_path)
16
+
17
+
18
+
19
+ # print(analyzer(["This production is good", "This product was quite expensive"]))
20
+
21
+ def sentiment_analyzer(review):
22
+ sentiment = analyzer(review)
23
+ return sentiment[0]['label']
24
+
25
+ def sentiment_bar_chart(df):
26
+ sentiment_counts = df['Sentiment'].value_counts()
27
+
28
+ # Create a bar chart
29
+ fig, ax = plt.subplots()
30
+ sentiment_counts.plot(kind='pie', ax=ax, autopct='%1.1f%%', color=['green', 'red'])
31
+ ax.set_title('Review Sentiment Counts')
32
+ ax.set_xlabel('Sentiment')
33
+ ax.set_ylabel('Count')
34
+ # ax.set_xticklabels(['Positive', 'Negative'], rotation=0)
35
 
36
+ # Return the figure object
37
+ return fig
38
 
 
 
 
39
 
 
40
  def read_reviews_and_analyze_sentiment(file_object):
41
+ # Load the Excel file into a DataFrame
42
+ df = pd.read_excel(file_object)
43
+
44
+ # Check if 'Review' column is in the DataFrame
45
+ if 'Reviews' not in df.columns:
46
+ raise ValueError("Excel file must contain a 'Review' column.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ # Apply the get_sentiment function to each review in the DataFrame
49
+ df['Sentiment'] = df['Reviews'].apply(sentiment_analyzer)
50
+ chart_object = sentiment_bar_chart(df)
51
+ return df, chart_object
52
+
53
+ # result = read_reviews_and_analyze_sentiment("../Files/Prod-review.xlsx")
54
+ # print(result)
55
+ # Example usage:
56
+ # df = read_reviews_and_analyze_sentiment('path_to_your_excel_file.xlsx')
57
+ # print(df)
58
 
 
59
 
60
  demo = gr.Interface(fn=read_reviews_and_analyze_sentiment,
61
+ inputs=[gr.File(file_types=["xlsx"], label="Upload your review comment file")],
62
+ outputs=[gr.Dataframe(label="Sentiments"), gr.Plot(label="Sentiment Analysis")],
63
+ title="@GenAILearniverse Project 3: Sentiment Analyzer",
64
+ description="THIS APPLICATION WILL BE USED TO ANALYZE THE SENTIMENT BASED ON FILE UPLAODED.")
65
+ demo.launch()
66
+
67
+
68
+
69
+
70
+
71
+
72
+ # Example usage:
73
+ # Assuming you have a dataframe `df` with appropriate data
74
+ # fig = sentiment_bar_chart(df)
75
+ # fig.show() # This line is just to visualize the plot in a local environment