OverMind0 commited on
Commit
813bfdd
·
verified ·
1 Parent(s): e3a5f53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -12
app.py CHANGED
@@ -4,29 +4,64 @@ 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
 
8
- # Load tokenizer
9
- with open("tokenizer.json", "r") as f:
10
- data = json.load(f)
11
- tokenizer = tokenizer_from_json(json.dumps(data))
 
 
12
 
13
- # Parameters
14
- max_tokens = 100 # Set this to the same as used during training
 
 
15
 
16
- # Load model
17
- model = load_model("review_amazon_sentiment5.h5")
 
 
 
 
18
 
19
- # Streamlit UI
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  st.title("Amazon Review Sentiment Analyzer")
21
  user_input = st.text_area("Enter an Amazon product review:")
22
 
23
  if st.button("Analyze"):
24
  if user_input.strip():
25
- tokens = tokenizer.texts_to_sequences([user_input])
26
- tokens_padded = pad_sequences(tokens, maxlen=max_tokens)
27
- pred_prob = model.predict(tokens_padded)[0][0]
 
28
  sentiment = "🟢 Positive" if pred_prob < 0.5 else "🔴 Negative"
 
 
29
  st.markdown(f"**Sentiment:** {sentiment}")
30
  st.markdown(f"**Confidence:** {pred_prob:.2f}")
 
 
 
 
 
 
31
  else:
32
  st.warning("Please enter some text to analyze.")
 
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):
34
+ fig = exp.as_pyplot_figure()
35
+ buf = BytesIO()
36
+ fig.savefig(buf, format="png", bbox_inches="tight")
37
+ st.image(buf.getvalue(), use_column_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.")