Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pickle
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import tensorflow as tf
|
| 7 |
+
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 8 |
+
|
| 9 |
+
# --- Load Preprocessing Objects ---
|
| 10 |
+
@st.cache_resource
|
| 11 |
+
def load_resources():
|
| 12 |
+
model = tf.keras.models.load_model("ensemble_model.keras")
|
| 13 |
+
with open("tokenizer.pkl", "rb") as f:
|
| 14 |
+
tokenizer = pickle.load(f)
|
| 15 |
+
with open("config.json", "r") as f:
|
| 16 |
+
config = json.load(f)
|
| 17 |
+
return model, tokenizer, config['max_length']
|
| 18 |
+
|
| 19 |
+
model, tokenizer, max_length = load_resources()
|
| 20 |
+
|
| 21 |
+
# --- Text Normalization ---
|
| 22 |
+
NON_ALPHANUM = re.compile(r'\W')
|
| 23 |
+
NON_ASCII = re.compile(r'[^a-z0-1\s]')
|
| 24 |
+
def normalize_text(text):
|
| 25 |
+
return NON_ASCII.sub('', NON_ALPHANUM.sub(' ', text.lower()))
|
| 26 |
+
|
| 27 |
+
# --- Inference ---
|
| 28 |
+
def predict_sentiment(text):
|
| 29 |
+
text = normalize_text(text)
|
| 30 |
+
sequence = tokenizer.texts_to_sequences([text])
|
| 31 |
+
padded = pad_sequences(sequence, maxlen=max_length)
|
| 32 |
+
prediction = model.predict(padded)[0][0]
|
| 33 |
+
sentiment = "Positive 😊" if prediction > 0.5 else "Negative 😞"
|
| 34 |
+
return sentiment, float(prediction)
|
| 35 |
+
|
| 36 |
+
# --- UI ---
|
| 37 |
+
st.title("🗣️ Sentiment Analysis of Customer Reviews")
|
| 38 |
+
st.markdown("This app uses a deep learning model to predict the **sentiment** of customer feedback — whether it's **positive** or **negative**.")
|
| 39 |
+
|
| 40 |
+
user_input = st.text_area("Enter a customer review:")
|
| 41 |
+
|
| 42 |
+
if st.button("Analyze"):
|
| 43 |
+
if user_input.strip() == "":
|
| 44 |
+
st.warning("Please enter some text to analyze.")
|
| 45 |
+
else:
|
| 46 |
+
sentiment, confidence = predict_sentiment(user_input)
|
| 47 |
+
st.subheader("Prediction")
|
| 48 |
+
st.write(f"**Sentiment:** {sentiment}")
|
| 49 |
+
st.write(f"**Confidence:** {confidence:.2%}")
|