arjahojnik commited on
Commit
a15fa3d
·
verified ·
1 Parent(s): bac4aa5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -32
app.py CHANGED
@@ -1,87 +1,113 @@
 
 
 
1
  import gradio as gr
2
  import numpy as np
3
  from tensorflow.keras.models import load_model
4
  from tensorflow.keras.preprocessing.sequence import pad_sequences
5
  import pickle
6
- import os
7
-
8
- os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # Disable GPU
9
-
10
 
 
11
  gru_model = load_model("best_GRU_tuning_model.h5")
12
  lstm_model = load_model("LSTM_model.h5")
13
  bilstm_model = load_model("BiLSTM_model.h5")
14
 
15
-
16
  with open("my_tokenizer.pkl", "rb") as f:
17
  tokenizer = pickle.load(f)
18
 
19
-
20
  def preprocess_text(text):
21
  text = text.lower()
22
  text = re.sub(r'[^a-zA-Z\s]', '', text).strip()
23
  return text
24
 
25
-
26
  def predict_sentiment(model, text):
 
 
 
27
  cleaned = preprocess_text(text)
 
 
 
28
  seq = tokenizer.texts_to_sequences([cleaned])
 
 
 
29
  padded_seq = pad_sequences(seq, maxlen=200)
30
  probs = model.predict(padded_seq)
31
  predicted_class = np.argmax(probs, axis=1)[0]
32
  rating = predicted_class + 1
33
  return rating, probs[0]
34
 
35
-
36
  def predict_all_models(text):
37
- gru_rating, gru_probs = predict_sentiment(gru_model, text)
38
- lstm_rating, lstm_probs = predict_sentiment(lstm_model, text)
39
- bilstm_rating, bilstm_probs = predict_sentiment(bilstm_model, text)
40
-
41
- ratings = [gru_rating, lstm_rating, bilstm_rating]
42
- lowest = min(ratings)
43
- highest = max(ratings)
44
- average = sum(ratings) / len(ratings)
45
-
46
- results = {
47
- "GRU Model": f"Predicted Rating: {gru_rating} (Probabilities: {gru_probs})",
48
- "LSTM Model": f"Predicted Rating: {lstm_rating} (Probabilities: {lstm_probs})",
49
- "BiLSTM Model": f"Predicted Rating: {bilstm_rating} (Probabilities: {bilstm_probs})",
50
- "Statistics": f"Lowest: {lowest}, Highest: {highest}, Average: {average:.2f}"
51
- }
52
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  return results
54
 
55
-
56
  def create_interface():
57
  with gr.Blocks() as demo:
58
  gr.Markdown("# Sentiment Analysis App")
59
  gr.Markdown("Predict the sentiment of your text review using RNN-based models.")
60
-
61
  with gr.Row():
62
  text_input = gr.Textbox(label="Enter your text here:", placeholder="Type your review here...")
63
-
64
  with gr.Row():
65
  gr.Markdown("### Predicted Sentiment")
66
  gru_output = gr.Textbox(label="GRU Model")
67
  lstm_output = gr.Textbox(label="LSTM Model")
68
  bilstm_output = gr.Textbox(label="BiLSTM Model")
69
-
70
  with gr.Row():
71
  gr.Markdown("### Statistics")
72
  stats_output = gr.Textbox(label="Lowest, Highest, Average")
73
-
 
74
  predict_button = gr.Button("Predict Sentiment")
75
-
 
76
  predict_button.click(
77
  fn=predict_all_models,
78
  inputs=text_input,
79
  outputs=[gru_output, lstm_output, bilstm_output, stats_output]
80
  )
81
-
82
  return demo
83
 
84
-
85
  if __name__ == "__main__":
86
  demo = create_interface()
87
  demo.launch()
 
1
+ import os
2
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # Disable GPU
3
+
4
  import gradio as gr
5
  import numpy as np
6
  from tensorflow.keras.models import load_model
7
  from tensorflow.keras.preprocessing.sequence import pad_sequences
8
  import pickle
9
+ import re # Added for text preprocessing
 
 
 
10
 
11
+ # Load your models
12
  gru_model = load_model("best_GRU_tuning_model.h5")
13
  lstm_model = load_model("LSTM_model.h5")
14
  bilstm_model = load_model("BiLSTM_model.h5")
15
 
16
+ # Load your tokenizer
17
  with open("my_tokenizer.pkl", "rb") as f:
18
  tokenizer = pickle.load(f)
19
 
20
+ # Preprocess text
21
  def preprocess_text(text):
22
  text = text.lower()
23
  text = re.sub(r'[^a-zA-Z\s]', '', text).strip()
24
  return text
25
 
26
+ # Predict sentiment using a model
27
  def predict_sentiment(model, text):
28
+ if not text or not text.strip(): # Check for empty input
29
+ return 0, [0, 0, 0, 0, 0] # Return default values for empty input
30
+
31
  cleaned = preprocess_text(text)
32
+ if not cleaned: # Check if cleaned text is empty
33
+ return 0, [0, 0, 0, 0, 0] # Return default values for invalid input
34
+
35
  seq = tokenizer.texts_to_sequences([cleaned])
36
+ if not seq or not seq[0]: # Check if tokenization failed
37
+ return 0, [0, 0, 0, 0, 0] # Return default values for invalid input
38
+
39
  padded_seq = pad_sequences(seq, maxlen=200)
40
  probs = model.predict(padded_seq)
41
  predicted_class = np.argmax(probs, axis=1)[0]
42
  rating = predicted_class + 1
43
  return rating, probs[0]
44
 
45
+ # Main prediction function
46
  def predict_all_models(text):
47
+ try:
48
+ # Predict with GRU
49
+ gru_rating, gru_probs = predict_sentiment(gru_model, text)
50
+ # Predict with LSTM
51
+ lstm_rating, lstm_probs = predict_sentiment(lstm_model, text)
52
+ # Predict with BiLSTM
53
+ bilstm_rating, bilstm_probs = predict_sentiment(bilstm_model, text)
54
+
55
+ # Calculate statistics
56
+ ratings = [gru_rating, lstm_rating, bilstm_rating]
57
+ lowest = min(ratings)
58
+ highest = max(ratings)
59
+ average = sum(ratings) / len(ratings)
60
+
61
+ # Format results
62
+ results = {
63
+ "GRU Model": f"Predicted Rating: {gru_rating} (Probabilities: {gru_probs})",
64
+ "LSTM Model": f"Predicted Rating: {lstm_rating} (Probabilities: {lstm_probs})",
65
+ "BiLSTM Model": f"Predicted Rating: {bilstm_rating} (Probabilities: {bilstm_probs})",
66
+ "Statistics": f"Lowest: {lowest}, Highest: {highest}, Average: {average:.2f}"
67
+ }
68
+ except Exception as e:
69
+ print(f"Error during prediction: {e}") # Debugging: Print the error
70
+ results = {
71
+ "GRU Model": "Error",
72
+ "LSTM Model": "Error",
73
+ "BiLSTM Model": "Error",
74
+ "Statistics": "Error"
75
+ }
76
+
77
  return results
78
 
79
+ # Gradio interface
80
  def create_interface():
81
  with gr.Blocks() as demo:
82
  gr.Markdown("# Sentiment Analysis App")
83
  gr.Markdown("Predict the sentiment of your text review using RNN-based models.")
84
+
85
  with gr.Row():
86
  text_input = gr.Textbox(label="Enter your text here:", placeholder="Type your review here...")
87
+
88
  with gr.Row():
89
  gr.Markdown("### Predicted Sentiment")
90
  gru_output = gr.Textbox(label="GRU Model")
91
  lstm_output = gr.Textbox(label="LSTM Model")
92
  bilstm_output = gr.Textbox(label="BiLSTM Model")
93
+
94
  with gr.Row():
95
  gr.Markdown("### Statistics")
96
  stats_output = gr.Textbox(label="Lowest, Highest, Average")
97
+
98
+ # Button to predict
99
  predict_button = gr.Button("Predict Sentiment")
100
+
101
+ # Event handler for the predict button
102
  predict_button.click(
103
  fn=predict_all_models,
104
  inputs=text_input,
105
  outputs=[gru_output, lstm_output, bilstm_output, stats_output]
106
  )
107
+
108
  return demo
109
 
110
+ # Launch the app
111
  if __name__ == "__main__":
112
  demo = create_interface()
113
  demo.launch()