Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import re, string
|
| 3 |
+
import joblib
|
| 4 |
+
import numpy as np
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
# -----------------------------
|
| 8 |
+
# 1️⃣ Load model and vectorizer
|
| 9 |
+
# -----------------------------
|
| 10 |
+
model = joblib.load("svm_model.pkl")
|
| 11 |
+
tfidf = joblib.load("tfidf_vectorizer.pkl")
|
| 12 |
+
|
| 13 |
+
# -----------------------------
|
| 14 |
+
# 2️⃣ Preprocess function
|
| 15 |
+
# -----------------------------
|
| 16 |
+
def preprocess(text):
|
| 17 |
+
text = str(text).lower()
|
| 18 |
+
text = re.sub(f"[{string.punctuation}]", "", text)
|
| 19 |
+
text = re.sub(r"\d+", "", text)
|
| 20 |
+
text = text.strip()
|
| 21 |
+
return text
|
| 22 |
+
|
| 23 |
+
# -----------------------------
|
| 24 |
+
# 3️⃣ Prediction function
|
| 25 |
+
# -----------------------------
|
| 26 |
+
def predict_sentiment(review):
|
| 27 |
+
if not review:
|
| 28 |
+
return "Error: No review provided", 0.0
|
| 29 |
+
cleaned = preprocess(review)
|
| 30 |
+
vectorized = tfidf.transform([cleaned])
|
| 31 |
+
|
| 32 |
+
pred = model.predict(vectorized)[0]
|
| 33 |
+
sentiment = "positive" if pred == 1 else "negative"
|
| 34 |
+
|
| 35 |
+
confidence = model.decision_function(vectorized)[0]
|
| 36 |
+
confidence = 1 / (1 + np.exp(-confidence)) # sigmoid for probability-like score
|
| 37 |
+
|
| 38 |
+
return sentiment, round(float(confidence)*100, 2)
|
| 39 |
+
|
| 40 |
+
# -----------------------------
|
| 41 |
+
# 4️⃣ Gradio UI
|
| 42 |
+
# -----------------------------
|
| 43 |
+
iface = gr.Interface(
|
| 44 |
+
fn=predict_sentiment,
|
| 45 |
+
inputs=gr.Textbox(label="Write a review here...", lines=5, placeholder="Type your review..."),
|
| 46 |
+
outputs=[
|
| 47 |
+
gr.Label(label="Predicted Sentiment"),
|
| 48 |
+
gr.Number(label="Confidence (%)")
|
| 49 |
+
],
|
| 50 |
+
title="Amazon Review Sentiment Analysis",
|
| 51 |
+
description="Enter an Amazon product review and get the predicted sentiment along with confidence score.",
|
| 52 |
+
theme="default"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# -----------------------------
|
| 56 |
+
# 5️⃣ Launch
|
| 57 |
+
# -----------------------------
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
iface.launch()
|