atdokmeci commited on
Commit
86fa84f
·
verified ·
1 Parent(s): 0b15b1e

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +17 -45
src/streamlit_app.py CHANGED
@@ -1,83 +1,55 @@
1
- # import streamlit as st
2
- # import numpy as np
3
- # from tensorflow.keras.models import load_model
4
- # import joblib
5
-
6
- # st.title('Sentiment Analysis Prediction')
7
-
8
- # # Load the model and preprocessor
9
- # try:
10
- # model = load_model('src/cnn_model.keras')
11
- # preproc = joblib.load('src/preproc.joblib')
12
- # except Exception as e:
13
- # st.error(f"Error loading model or preprocessor: {e}")
14
-
15
- # # Input field for text
16
- # text_input = st.text_area('Enter text for sentiment analysis:', '')
17
-
18
- # if st.button('Predict Sentiment'):
19
- # if not text_input.strip():
20
- # st.warning('Please enter some text.')
21
- # else:
22
- # try:
23
- # # Preprocess input text
24
- # X = preproc.transform([text_input])
25
- # # Predict sentiment
26
- # prediction = model.predict(X)
27
- # # Assuming binary classification: 0=Negative, 1=Positive
28
- # sentiment = 'Positive' if prediction[0][0] > 0.5 else 'Negative'
29
- # st.success(f'Prediction: {sentiment} (score: {prediction[0][0]:.2f})')
30
- # except Exception as e:
31
- # st.error(f"Error making prediction: {e
32
-
33
 
34
  import streamlit as st
35
  import numpy as np
36
  from tensorflow.keras.models import load_model
37
  import joblib
 
38
 
39
  st.title('Sentiment Analysis Prediction')
40
 
 
 
 
 
41
  # Load the model and preprocessor
42
  try:
43
- model = load_model('src/cnn_model.keras')
44
- preproc = joblib.load('src/preproc.joblib')
45
  except Exception as e:
46
  st.error(f"Error loading model or preprocessor: {e}")
47
 
48
  text_input = st.text_area('Enter text for sentiment analysis:', '')
49
 
 
 
 
50
  def preprocess_text(text, preproc):
51
- # If preproc is a dict, try common keys
52
  if isinstance(preproc, dict):
53
  if 'tokenizer' in preproc:
54
- # Keras Tokenizer
55
  tokenizer = preproc['tokenizer']
56
  seq = tokenizer.texts_to_sequences([text])
57
- # Pad sequences if needed
58
- if 'padder' in preproc:
59
- padder = preproc['padder']
60
- seq = padder(seq)
61
- return np.array(seq)
62
  elif 'vectorizer' in preproc:
63
- # scikit-learn TfidfVectorizer or similar
64
  vectorizer = preproc['vectorizer']
65
  return vectorizer.transform([text])
66
  else:
67
  raise ValueError("Unknown preprocessor dict keys.")
68
  else:
69
- # If preproc is a single object
70
  if hasattr(preproc, 'transform'):
71
  return preproc.transform([text])
72
  elif hasattr(preproc, 'texts_to_sequences'):
73
  seq = preproc.texts_to_sequences([text])
74
- return np.array(seq)
 
75
  else:
76
  raise ValueError("Unknown preprocessor type.")
77
 
78
  if st.button('Predict Sentiment'):
79
  if not text_input.strip():
80
  st.warning('Please enter some text.')
 
 
81
  else:
82
  try:
83
  X = preprocess_text(text_input, preproc)
@@ -85,4 +57,4 @@ if st.button('Predict Sentiment'):
85
  sentiment = 'Positive' if prediction[0][0] > 0.5 else 'Negative'
86
  st.success(f'Prediction: {sentiment} (score: {prediction[0][0]:.2f})')
87
  except Exception as e:
88
- st.error(f"Error making prediction: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
  import streamlit as st
3
  import numpy as np
4
  from tensorflow.keras.models import load_model
5
  import joblib
6
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
7
 
8
  st.title('Sentiment Analysis Prediction')
9
 
10
+ # Initialize model and preproc as None
11
+ model = None
12
+ preproc = None
13
+
14
  # Load the model and preprocessor
15
  try:
16
+ model = load_model('Sentiment Analyis/cnn/cnn_model.keras')
17
+ preproc = joblib.load('Sentiment Analyis/cnn/preproc.joblib')
18
  except Exception as e:
19
  st.error(f"Error loading model or preprocessor: {e}")
20
 
21
  text_input = st.text_area('Enter text for sentiment analysis:', '')
22
 
23
+ # Preprocess function with padding to match model input shape
24
+ MAXLEN = 60 # Change this if your model expects a different input length
25
+
26
  def preprocess_text(text, preproc):
 
27
  if isinstance(preproc, dict):
28
  if 'tokenizer' in preproc:
 
29
  tokenizer = preproc['tokenizer']
30
  seq = tokenizer.texts_to_sequences([text])
31
+ seq = pad_sequences(seq, maxlen=MAXLEN)
32
+ return seq
 
 
 
33
  elif 'vectorizer' in preproc:
 
34
  vectorizer = preproc['vectorizer']
35
  return vectorizer.transform([text])
36
  else:
37
  raise ValueError("Unknown preprocessor dict keys.")
38
  else:
 
39
  if hasattr(preproc, 'transform'):
40
  return preproc.transform([text])
41
  elif hasattr(preproc, 'texts_to_sequences'):
42
  seq = preproc.texts_to_sequences([text])
43
+ seq = pad_sequences(seq, maxlen=MAXLEN)
44
+ return seq
45
  else:
46
  raise ValueError("Unknown preprocessor type.")
47
 
48
  if st.button('Predict Sentiment'):
49
  if not text_input.strip():
50
  st.warning('Please enter some text.')
51
+ elif model is None or preproc is None:
52
+ st.error('Model or preprocessor not loaded. Please check the files and try again.')
53
  else:
54
  try:
55
  X = preprocess_text(text_input, preproc)
 
57
  sentiment = 'Positive' if prediction[0][0] > 0.5 else 'Negative'
58
  st.success(f'Prediction: {sentiment} (score: {prediction[0][0]:.2f})')
59
  except Exception as e:
60
+ st.error(f"Error making prediction: {e}")