Karan0310 commited on
Commit
7d3dd51
·
verified ·
1 Parent(s): 6a92029

Upload SentimentAnalyzer.py

Browse files
Files changed (1) hide show
  1. SentimentAnalyzer.py +86 -0
SentimentAnalyzer.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import re
3
+ import gradio as gr
4
+ import pandas as pd
5
+ import matplotlib.pyplot as plt
6
+ from pydantic import BaseModel, PydanticUserError, ConfigDict
7
+ from pydantic import BaseModel, ConfigDict
8
+
9
+ class MyModel(BaseModel):
10
+ request: 'starlette.requests.Request'
11
+ model_config = ConfigDict(arbitrary_types_allowed=True)
12
+ from pydantic_core import core_schema
13
+ from starlette.requests import Request
14
+
15
+ def get_pydantic_core_schema(request_type, handler):
16
+ return core_schema.any_schema()
17
+
18
+ Request.__get_pydantic_core_schema__ = get_pydantic_core_schema
19
+
20
+
21
+ from transformers import pipeline
22
+
23
+ pipe = pipeline("text-classification",
24
+ model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
25
+
26
+
27
+
28
+ analyzer=pipeline(task="text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
29
+
30
+
31
+ def sentiment_analyzer(review):
32
+ sentiment = analyzer(review)
33
+ return sentiment[0]['label']
34
+
35
+ def sentiment_bar_chart(df):
36
+ sentiment_counts=df['Sentiment'].value_counts()
37
+
38
+ fig, ax=plt.subplots()
39
+ sentiment_counts.plot(kind='pie', ax=ax, autopct='%1.1f%%', color=['green', 'red'])
40
+ ax.set_title('Review Sentiment Counts')
41
+ ax.set_xlabel('Sentiment')
42
+ ax.set_ylabel('Count')
43
+ #ax.set_xticklabels(['Positive', 'Negative'], rotation=0)
44
+
45
+ return fig
46
+
47
+
48
+ def get_sentiment(review):
49
+ from textblob import TextBlob
50
+ analysis=TextBlob(review)
51
+ return analysis.sentiment.polarity
52
+
53
+ def read_reviews_and_analyze_sentiment(file_object):
54
+ print("file_obj received:", file_object)
55
+
56
+ # Handle file path or file object
57
+ if hasattr(file_object, 'name'):
58
+ file_name = file_object.name
59
+ else:
60
+ file_name = file_object
61
+
62
+ # Read file based on extension
63
+ if str(file_name).lower().endswith('.csv'):
64
+ df = pd.read_csv(file_object)
65
+ elif str(file_name).lower().endswith(('.xlsx', '.xls', '.xlsm', '.xlsb', '.ods', '.odt')):
66
+ df = pd.read_excel(file_object)
67
+ else:
68
+ raise ValueError("Unsupported file type. Please upload a CSV or Excel file.")
69
+
70
+ df['Sentiment']=df['Reviews'].apply(sentiment_analyzer)
71
+ chart_object=sentiment_bar_chart(df)
72
+
73
+ return df, chart_object
74
+
75
+
76
+ gr.close_all()
77
+ demo = gr.Interface(
78
+ fn=read_reviews_and_analyze_sentiment,
79
+ inputs=gr.File(file_types=['.xlsx','csv'], label='Upload your review comment file'),
80
+ outputs=[gr.Dataframe(label='Sentiments'), gr.Plot(label='Sentiment Analysis')],
81
+ title='KS Sentiment Analyzer',
82
+ description='This application will classify the sentiment of reviews based on an uploaded Excel file. The file must contain a column named "Reviews".'
83
+ )
84
+
85
+ demo.launch(share=True)
86
+