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()