File size: 1,763 Bytes
a4653e1 |
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 |
# 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() |