File size: 4,031 Bytes
2fc64ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66b94e2
2fc64ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import torch
import gradio as gr
import pandas as pd
import matplotlib.pyplot as plt
from transformers import pipeline
import tempfile
import os

# ---------------- LOAD MODEL ----------------

print("Loading sentiment model...")

# model_path = (
#     "../Models/models--distilbert--distilbert-base-uncased-finetuned-sst-2-english"
#     "/snapshots/714eb0fa89d2f80546fda750413ed43d93601a13"
# )

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

print("Model loaded.")

# ---------------- SINGLE REVIEW ----------------

def sentiment_analyzer(review):
    result = analyzer(review)[0]
    return f"{result['label']} (Confidence: {round(result['score'], 4)})"


# ---------------- EXCEL + VISUALIZATION ----------------

def analyze_excel(file):
    df = pd.read_excel(file.name)

    if "review" not in df.columns:
        return None, None, None, None

    sentiments = []
    scores = []

    for review in df["review"]:
        result = analyzer(review)[0]
        sentiments.append(result["label"])
        scores.append(round(result["score"], 4))

    df["sentiment"] = sentiments
    df["confidence_score"] = scores

    # ---- Sentiment counts ----
    counts = df["sentiment"].value_counts()

    # ---- Bar Chart ----
    fig_bar = plt.figure()
    counts.plot(
        kind="bar",
        color=["#22c55e", "#ef4444"],
        xlabel="Sentiment",
        ylabel="Number of Reviews",
        title="Sentiment Distribution (Bar Chart)"
    )
    plt.xticks(rotation=0)
    plt.tight_layout()

    # ---- Pie Chart ----
    fig_pie = plt.figure()
    counts.plot(
        kind="pie",
        autopct="%1.1f%%",
        startangle=90,
        colors=["#22c55e", "#ef4444"],
        ylabel="",
        title="Sentiment Distribution (Pie Chart)"
    )
    plt.tight_layout()

    # ---- Save Excel for download ----
    tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
    df.to_excel(tmp_file.name, index=False)

    return df, fig_bar, fig_pie, tmp_file.name


# ---------------- GRADIO UI ----------------

with gr.Blocks(theme=gr.themes.Soft(), title="Gen AI Project 3: Sentiment Analyzer") as demo:

    gr.Markdown("""
    Gen AI Project 3: Sentiment Analyzer  
    Analyze **individual reviews** or **bulk Excel reviews** using a fine-tuned **DistilBERT** model.  
    Get **AI insights + visual analytics + downloadable results**.
    """)

    with gr.Tabs():

        # -------- SINGLE REVIEW TAB --------
        with gr.Tab("πŸ“ Single Review"):
            with gr.Row():
                review_input = gr.Textbox(
                    label="Enter Review Text",
                    placeholder="e.g. I absolutely loved this product!",
                    lines=4
                )
                sentiment_output = gr.Textbox(label="Predicted Sentiment")

            gr.Button("Analyze Sentiment πŸš€").click(
                fn=sentiment_analyzer,
                inputs=review_input,
                outputs=sentiment_output
            )

        # -------- EXCEL TAB --------
        with gr.Tab("πŸ“Š Excel Upload & Analysis"):
            file_input = gr.File(
                label="Upload Excel File (.xlsx)",
                file_types=[".xlsx"]
            )

            analyze_btn = gr.Button("Analyze Excel πŸ“ˆ")

            df_output = gr.Dataframe(label="Sentiment Results Table")
            bar_output = gr.Plot(label="Bar Chart")
            pie_output = gr.Plot(label="Pie Chart")
            download_output = gr.File(label="Download Analyzed Excel")

            analyze_btn.click(
                fn=analyze_excel,
                inputs=file_input,
                outputs=[df_output, bar_output, pie_output, download_output]
            )

    gr.Markdown("""
    ---
    βœ… **Tech Stack:** Python, Transformers, DistilBERT, Pandas, Matplotlib, Gradio  
    πŸš€ **Use Case:** Product reviews, customer feedback, social media sentiment  
    """)

demo.launch()