File size: 2,124 Bytes
2f400ca
c7992da
aa023d7
 
 
86fa84f
aa023d7
 
 
86fa84f
 
 
 
aa023d7
 
23e750b
 
aa023d7
 
 
 
 
86fa84f
 
 
2f400ca
 
 
 
 
86fa84f
 
2f400ca
 
 
 
 
 
 
 
 
 
86fa84f
 
2f400ca
 
 
aa023d7
 
 
86fa84f
 
aa023d7
 
2f400ca
aa023d7
257829e
 
aa023d7
86fa84f
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

import streamlit as st
import numpy as np
from tensorflow.keras.models import load_model
import joblib
from tensorflow.keras.preprocessing.sequence import pad_sequences

st.title('Sentiment Analysis Prediction')

# Initialize model and preproc as None
model = None
preproc = None

# Load the model and preprocessor
try:
    model = load_model('src/cnn_model.keras')
    preproc = joblib.load('src/preproc.joblib')
except Exception as e:
    st.error(f"Error loading model or preprocessor: {e}")

text_input = st.text_area('Enter text for sentiment analysis:', '')

# Preprocess function with padding to match model input shape
MAXLEN = 60  # Change this if your model expects a different input length

def preprocess_text(text, preproc):
    if isinstance(preproc, dict):
        if 'tokenizer' in preproc:
            tokenizer = preproc['tokenizer']
            seq = tokenizer.texts_to_sequences([text])
            seq = pad_sequences(seq, maxlen=MAXLEN)
            return seq
        elif 'vectorizer' in preproc:
            vectorizer = preproc['vectorizer']
            return vectorizer.transform([text])
        else:
            raise ValueError("Unknown preprocessor dict keys.")
    else:
        if hasattr(preproc, 'transform'):
            return preproc.transform([text])
        elif hasattr(preproc, 'texts_to_sequences'):
            seq = preproc.texts_to_sequences([text])
            seq = pad_sequences(seq, maxlen=MAXLEN)
            return seq
        else:
            raise ValueError("Unknown preprocessor type.")

if st.button('Predict Sentiment'):
    if not text_input.strip():
        st.warning('Please enter some text.')
    elif model is None or preproc is None:
        st.error('Model or preprocessor not loaded. Please check the files and try again.')
    else:
        try:
            X = preprocess_text(text_input, preproc)
            prediction = model.predict(X)
            sentiment = 'Positive' if prediction[0][0] < 0.5 else 'Negative'
            st.success(f'Prediction: {sentiment}')
        except Exception as e:
            st.error(f"Error making prediction: {e}")