chandu1617's picture
Create app.py
a4653e1 verified
# app.py
import re, string
import joblib
import numpy as np
import gradio as gr
# -----------------------------
# 1️⃣ Load model and vectorizer
# -----------------------------
model = joblib.load("svm_model.pkl")
tfidf = joblib.load("tfidf_vectorizer.pkl")
# -----------------------------
# 2️⃣ Preprocess function
# -----------------------------
def preprocess(text):
text = str(text).lower()
text = re.sub(f"[{string.punctuation}]", "", text)
text = re.sub(r"\d+", "", text)
text = text.strip()
return text
# -----------------------------
# 3️⃣ Prediction function
# -----------------------------
def predict_sentiment(review):
if not review:
return "Error: No review provided", 0.0
cleaned = preprocess(review)
vectorized = tfidf.transform([cleaned])
pred = model.predict(vectorized)[0]
sentiment = "positive" if pred == 1 else "negative"
confidence = model.decision_function(vectorized)[0]
confidence = 1 / (1 + np.exp(-confidence)) # sigmoid for probability-like score
return sentiment, round(float(confidence)*100, 2)
# -----------------------------
# 4️⃣ Gradio UI
# -----------------------------
iface = gr.Interface(
fn=predict_sentiment,
inputs=gr.Textbox(label="Write a review here...", lines=5, placeholder="Type your review..."),
outputs=[
gr.Label(label="Predicted Sentiment"),
gr.Number(label="Confidence (%)")
],
title="Amazon Review Sentiment Analysis",
description="Enter an Amazon product review and get the predicted sentiment along with confidence score.",
theme="default"
)
# -----------------------------
# 5️⃣ Launch
# -----------------------------
if __name__ == "__main__":
iface.launch()