File size: 2,048 Bytes
5ac2959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import gradio as gr
import pandas as pd
import matplotlib.pyplot as plt

# Use a pipeline as a high-level helper
from transformers import pipeline
# model_path = ("../.venv/Modal/models--distilbert--distilbert-base-uncased-finetuned-sst-2-english"
#              "/snapshots/714eb0fa89d2f80546fda750413ed43d93601a13")

analyzer = pipeline("text-classification",
                model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")


# analyzer = pipeline("text-classification",
#                 model=model_path)

# print(analyzer(["This product is good", "This product was quite expensive"]))

def sentiment_analyzer(review):
    sentiment = analyzer(review)
    return sentiment[0]['label']

def sentiment_bar_chart(df):
    sentiment_counts = df['Sentiment'].value_counts()

    # Create a bar chart
    fig, ax = plt.subplots()
    sentiment_counts.plot(kind='pie', ax=ax, autopct='%1.1f%%', color=['green', 'red'])
    ax.set_title('Review Sentiment Counts')
    ax.set_xlabel('Sentiment')
    ax.set_ylabel('Count')
    # ax.set_xticklabels(['Positive', 'Negative'], rotation=0)

    # Return the figure object
    return fig

def read_reviews_and_analyze_sentiment(file_object):
    df = pd.read_excel(file_object)

    if 'Reviews' not in df.columns:
        raise ValueError("Error file must contains a 'Reviews' column.")

    df['Sentiment'] = df['Reviews'].apply(sentiment_analyzer)
    chart_object = sentiment_bar_chart(df)
    return df, chart_object

# result = read_reviews_and_analyze_sentiment("../.venv/Files/reviews-sentiment.xlsx")
# print(result)

demo = gr.Interface(fn=read_reviews_and_analyze_sentiment,
                    inputs=[gr.File(file_types=[".xlsx"], label="Input your review comment file")],
                    outputs=[gr.Dataframe(label="Sentiment"), gr.Plot(label="Sentiment Analysis")],
                    title="Project 3: Sentiment Analyzer",
                    description="THIS APPLICATIONS WILL BE USED TO ANALYZER THE SENTIMENT BASED ON FILE UPLOADED.")

demo.launch()