File size: 3,361 Bytes
e0f7d84
bae1fbd
 
 
 
 
 
 
 
 
 
 
 
 
2b17fdb
 
bae1fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0f7d84
bae1fbd
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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)")