MovieReviewsSentimentAnalysis / src /streamlit_app.py
handex's picture
Update src/streamlit_app.py
2b17fdb verified
Raw
History Blame Contribute Delete
3.36 kB
import streamlit as st
import pickle
import re
import pandas as pd
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import SnowballStemmer
import nltk
# -------------------------------------------------------------
# 1. Constant Assets and Loading
# -------------------------------------------------------------
# NLTK Components (Ensure data is available for HF Spaces/Streamlit)
stop_words = set(stopwords.words('english'))
nltk.data.find('tokenizers/punkt')
ss = SnowballStemmer('english')
# Load Model and Vectorizer (Using Streamlit's cache for efficiency)
@st.cache_resource
def load_assets():
try:
# Load the trained model and vectorizer
with open('src/movie_sentiment.pkl', 'rb') as f:
loaded_model = pickle.load(f)
with open('src/count_vectorizer.pkl', 'rb') as f:
loaded_cv = pickle.load(f)
return loaded_model, loaded_cv
except FileNotFoundError:
st.error("Error: Model or Vectorizer files not found. Please check your file names.")
return None, None
loaded_model, loaded_cv = load_assets()
# -------------------------------------------------------------
# 2. STREAMLIT Interface
# -------------------------------------------------------------
st.title("🎬 Movie Review Sentiment Analysis")
st.markdown("Use the trained model to predict whether the entered review is **Positive** or **Negative**.")
# User Input
review_new = st.text_area("Enter Your Review Here:", height=150)
# Prediction Button
if st.button("Predict Sentiment") and loaded_model and loaded_cv:
if not review_new:
st.warning("Please enter a review to make a prediction.")
else:
# --- Start Prediction Process ---
# 1. PREPROCESSING CHAIN (Without separate function definitions)
# a) Remove HTML Tags (mimics the 'clean' function)
clean_html = re.sub(r'<.*?>', '', review_new)
# b) Replace Special Characters with Space (mimics the 'is_special' function)
# It replaces non-alphanumeric and non-whitespace chars with a space
clean_special = re.sub(r'[^a-zA-Z0-9\s]', ' ', clean_html)
# c) Convert to Lowercase
review_lower = clean_special.lower()
# d) NLTK Operations (Stopwords Removal and Stemming)
# Tokenization
words = word_tokenize(review_lower)
# Stopwords Removal and Stemming using list comprehension
# Filters out stop words and empty strings, then stems the rest
review_cleaned_list = [ss.stem(w) for w in words if w not in stop_words and w.strip() != '']
# Join back into a single string
review_cleaned_string = " ".join(review_cleaned_list)
# 2. VECTORIZATION
# The vectorizer expects a Series/list of strings, so we wrap the result
review_vectorized = loaded_cv.transform(pd.Series([review_cleaned_string])).toarray()
# 3. PREDICTION
prediction = loaded_model.predict(review_vectorized)[0]
# 4. DISPLAY RESULT
st.subheader("Prediction Result:")
if prediction == 1:
st.success(f"**The sentiment is POSITIVE πŸ˜ƒ** (Predicted Label: 1)")
else:
st.error(f"**The sentiment is NEGATIVE 😞** (Predicted Label: 0)")