Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,27 +4,30 @@ from tensorflow.keras.preprocessing.text import tokenizer_from_json
|
|
| 4 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 5 |
import json
|
| 6 |
import numpy as np
|
|
|
|
| 7 |
from lime.lime_text import LimeTextExplainer
|
| 8 |
-
from io import BytesIO
|
| 9 |
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
# --- Load
|
| 12 |
@st.cache_resource
|
| 13 |
def load_tokenizer():
|
| 14 |
with open("tokenizer.json", "r") as f:
|
| 15 |
data = json.load(f)
|
| 16 |
return tokenizer_from_json(json.dumps(data))
|
| 17 |
|
|
|
|
| 18 |
@st.cache_resource
|
| 19 |
def load_sentiment_model():
|
| 20 |
return load_model("review_amazon_sentiment5.h5")
|
| 21 |
|
| 22 |
-
# --- Predict function
|
| 23 |
def predict_proba(texts):
|
| 24 |
sequences = tokenizer.texts_to_sequences(texts)
|
| 25 |
padded = pad_sequences(sequences, maxlen=max_tokens)
|
| 26 |
preds = model.predict(padded)
|
| 27 |
-
return np.hstack([1 - preds, preds])
|
| 28 |
|
| 29 |
# --- Visualize explanation ---
|
| 30 |
def plot_explanation(exp):
|
|
@@ -33,39 +36,32 @@ def plot_explanation(exp):
|
|
| 33 |
fig.savefig(buf, format="png", bbox_inches="tight")
|
| 34 |
st.image(buf.getvalue(), use_container_width=True)
|
| 35 |
|
| 36 |
-
# ---
|
| 37 |
tokenizer = load_tokenizer()
|
| 38 |
model = load_sentiment_model()
|
| 39 |
max_tokens = 166
|
| 40 |
explainer = LimeTextExplainer(class_names=["Positive", "Negative"])
|
| 41 |
|
| 42 |
# --- Streamlit UI ---
|
| 43 |
-
st.
|
| 44 |
-
st.
|
| 45 |
-
st.markdown("Analyze the sentiment of any Amazon product review using a deep learning model. π")
|
| 46 |
|
| 47 |
-
|
| 48 |
-
user_input = st.text_area("βοΈ Enter an Amazon review", height=150, placeholder="Type or paste your review here...")
|
| 49 |
-
|
| 50 |
-
# --- Analyze Button ---
|
| 51 |
-
if st.button("π Analyze"):
|
| 52 |
if user_input.strip():
|
| 53 |
-
#
|
| 54 |
sequence = tokenizer.texts_to_sequences([user_input])
|
| 55 |
padded = pad_sequences(sequence, maxlen=max_tokens)
|
| 56 |
pred_prob = model.predict(padded)[0][0]
|
| 57 |
-
|
| 58 |
sentiment = "π’ Positive" if pred_prob < 0.5 else "π΄ Negative"
|
| 59 |
-
confidence = 1 - pred_prob if pred_prob < 0.5 else pred_prob
|
| 60 |
|
| 61 |
-
#
|
| 62 |
-
st.markdown(f"
|
| 63 |
-
st.
|
| 64 |
|
| 65 |
-
# LIME
|
| 66 |
-
with st.spinner("
|
| 67 |
explanation = explainer.explain_instance(user_input, predict_proba, num_features=10)
|
| 68 |
-
|
| 69 |
-
|
| 70 |
else:
|
| 71 |
-
st.warning("
|
|
|
|
| 4 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 5 |
import json
|
| 6 |
import numpy as np
|
| 7 |
+
import lime
|
| 8 |
from lime.lime_text import LimeTextExplainer
|
|
|
|
| 9 |
import matplotlib.pyplot as plt
|
| 10 |
+
import base64
|
| 11 |
+
from io import BytesIO
|
| 12 |
|
| 13 |
+
# --- Load tokenizer ---
|
| 14 |
@st.cache_resource
|
| 15 |
def load_tokenizer():
|
| 16 |
with open("tokenizer.json", "r") as f:
|
| 17 |
data = json.load(f)
|
| 18 |
return tokenizer_from_json(json.dumps(data))
|
| 19 |
|
| 20 |
+
# --- Load model ---
|
| 21 |
@st.cache_resource
|
| 22 |
def load_sentiment_model():
|
| 23 |
return load_model("review_amazon_sentiment5.h5")
|
| 24 |
|
| 25 |
+
# --- Predict function ---
|
| 26 |
def predict_proba(texts):
|
| 27 |
sequences = tokenizer.texts_to_sequences(texts)
|
| 28 |
padded = pad_sequences(sequences, maxlen=max_tokens)
|
| 29 |
preds = model.predict(padded)
|
| 30 |
+
return np.hstack([1 - preds, preds]) # For LIME binary classifier
|
| 31 |
|
| 32 |
# --- Visualize explanation ---
|
| 33 |
def plot_explanation(exp):
|
|
|
|
| 36 |
fig.savefig(buf, format="png", bbox_inches="tight")
|
| 37 |
st.image(buf.getvalue(), use_container_width=True)
|
| 38 |
|
| 39 |
+
# --- Initialize ---
|
| 40 |
tokenizer = load_tokenizer()
|
| 41 |
model = load_sentiment_model()
|
| 42 |
max_tokens = 166
|
| 43 |
explainer = LimeTextExplainer(class_names=["Positive", "Negative"])
|
| 44 |
|
| 45 |
# --- Streamlit UI ---
|
| 46 |
+
st.title("Amazon Review Sentiment Analyzer")
|
| 47 |
+
user_input = st.text_area("Enter an Amazon product review:")
|
|
|
|
| 48 |
|
| 49 |
+
if st.button("Analyze"):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
if user_input.strip():
|
| 51 |
+
# Predict
|
| 52 |
sequence = tokenizer.texts_to_sequences([user_input])
|
| 53 |
padded = pad_sequences(sequence, maxlen=max_tokens)
|
| 54 |
pred_prob = model.predict(padded)[0][0]
|
|
|
|
| 55 |
sentiment = "π’ Positive" if pred_prob < 0.5 else "π΄ Negative"
|
|
|
|
| 56 |
|
| 57 |
+
# Show Result
|
| 58 |
+
st.markdown(f"**Sentiment:** {sentiment}")
|
| 59 |
+
st.markdown(f"**Confidence:** {pred_prob:.2f}")
|
| 60 |
|
| 61 |
+
# Explain with LIME
|
| 62 |
+
with st.spinner("Explaining prediction..."):
|
| 63 |
explanation = explainer.explain_instance(user_input, predict_proba, num_features=10)
|
| 64 |
+
st.markdown("### π Why this prediction?")
|
| 65 |
+
plot_explanation(explanation)
|
| 66 |
else:
|
| 67 |
+
st.warning("Please enter some text to analyze.")
|