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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -80
app.py CHANGED
@@ -1,12 +1,12 @@
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")
@@ -17,97 +17,123 @@ bilstm_model = load_model("BiLSTM_model.h5")
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()
 
1
  import os
2
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
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
10
 
11
  # Load your models
12
  gru_model = load_model("best_GRU_tuning_model.h5")
 
17
  with open("my_tokenizer.pkl", "rb") as f:
18
  tokenizer = pickle.load(f)
19
 
20
+ # Preprocessing function for GRU, LSTM, and BiLSTM
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
+ # GRU prediction function
27
+ def predict_with_gru(text):
 
 
 
28
  cleaned = preprocess_text(text)
 
 
 
29
  seq = tokenizer.texts_to_sequences([cleaned])
30
+ padded_seq = pad_sequences(seq, maxlen=200)
31
+ probs = gru_model.predict(padded_seq)
 
 
 
32
  predicted_class = np.argmax(probs, axis=1)[0]
33
+ return int(predicted_class + 1)
 
34
 
35
+ # LSTM prediction function
36
+ def predict_with_lstm(text):
37
+ cleaned = preprocess_text(text)
38
+ seq = tokenizer.texts_to_sequences([cleaned])
39
+ padded_seq = pad_sequences(seq, maxlen=200)
40
+ probs = lstm_model.predict(padded_seq)
41
+ predicted_class = np.argmax(probs, axis=1)[0]
42
+ return int(predicted_class + 1)
43
+
44
+ # BiLSTM prediction function
45
+ def predict_with_bilstm(text):
46
+ cleaned = preprocess_text(text)
47
+ seq = tokenizer.texts_to_sequences([cleaned])
48
+ padded_seq = pad_sequences(seq, maxlen=200)
49
+ probs = bilstm_model.predict(padded_seq)
50
+ predicted_class = np.argmax(probs, axis=1)[0]
51
+ return int(predicted_class + 1)
52
+
53
+ # Unified function for sentiment analysis and statistics
54
+ def analyze_sentiment_and_statistics(text):
55
+ results = {
56
+ "GRU Model": predict_with_gru(text),
57
+ "LSTM Model": predict_with_lstm(text),
58
+ "BiLSTM Model": predict_with_bilstm(text),
59
+ }
60
+
61
+ # Calculate statistics
62
+ scores = list(results.values())
63
+ min_score = min(scores)
64
+ max_score = max(scores)
65
+ min_score_models = [model for model, score in results.items() if score == min_score]
66
+ max_score_models = [model for model, score in results.items() if score == max_score]
67
+ average_score = np.mean(scores)
68
+
69
+ if all(score == scores[0] for score in scores):
70
+ statistics = {
71
+ "Message": "All models predict the same score.",
72
+ "Average Score": f"{average_score:.2f}",
73
  }
74
+ else:
75
+ statistics = {
76
+ "Lowest Score": f"{min_score} (Models: {', '.join(min_score_models)})",
77
+ "Highest Score": f"{max_score} (Models: {', '.join(max_score_models)})",
78
+ "Average Score": f"{average_score:.2f}",
 
 
79
  }
80
+ return results, statistics
 
81
 
82
+ # Gradio Interface
83
+ with gr.Blocks(css=".gradio-container { max-width: 900px; margin: auto; padding: 20px; }") as demo:
84
+ gr.Markdown("# RNN Sentiment Analysis")
85
+ gr.Markdown(
86
+ "Predict the sentiment of your text review using RNN-based models."
87
+ )
88
+
89
+ with gr.Row():
90
+ with gr.Column():
91
+ text_input = gr.Textbox(
92
+ label="Enter your text here:",
93
+ lines=3,
94
+ placeholder="Type your review here..."
95
+ )
 
 
 
 
96
 
97
+ with gr.Column():
98
+ analyze_button = gr.Button("Analyze Sentiment")
99
+
100
+ with gr.Row():
101
+ with gr.Column():
102
+ gru_output = gr.Textbox(label="Predicted Sentiment (GRU Model)", interactive=False)
103
+ lstm_output = gr.Textbox(label="Predicted Sentiment (LSTM Model)", interactive=False)
104
+ bilstm_output = gr.Textbox(label="Predicted Sentiment (BiLSTM Model)", interactive=False)
105
 
106
+ with gr.Column():
107
+ statistics_output = gr.Textbox(label="Statistics (Lowest, Highest, Average)", interactive=False)
108
+
109
+ # Button to analyze sentiment and show statistics
110
+ def process_input_and_analyze(text_input):
111
+ results, statistics = analyze_sentiment_and_statistics(text_input)
112
+ if "Message" in statistics:
113
+ return (
114
+ f"{results['GRU Model']}",
115
+ f"{results['LSTM Model']}",
116
+ f"{results['BiLSTM Model']}",
117
+ f"Statistics:\n{statistics['Message']}\nAverage Score: {statistics['Average Score']}"
118
+ )
119
+ else:
120
+ return (
121
+ f"{results['GRU Model']}",
122
+ f"{results['LSTM Model']}",
123
+ f"{results['BiLSTM Model']}",
124
+ f"Statistics:\n{statistics['Lowest Score']}\n{statistics['Highest Score']}\nAverage Score: {statistics['Average Score']}"
125
+ )
126
 
127
+ analyze_button.click(
128
+ process_input_and_analyze,
129
+ inputs=[text_input],
130
+ outputs=[
131
+ gru_output,
132
+ lstm_output,
133
+ bilstm_output,
134
+ statistics_output
135
+ ]
136
+ )
137
 
138
  # Launch the app
139
+ demo.launch()