zafirabdullah12 commited on
Commit
d44ba12
Β·
verified Β·
1 Parent(s): 9624bb7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -63
app.py CHANGED
@@ -1,10 +1,13 @@
1
  # Importing Libraries
2
  import os
3
- os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # Force TensorFlow to use CPU only
 
 
4
  os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
5
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Suppress all TensorFlow messages
6
- os.environ['GRADIO_HOT_RELOAD'] = 'false' # Disable Gradio hot reload
7
  os.environ['WRAPT_DISABLE_EXTENSIONS'] = 'true'
 
8
 
9
  import re
10
  import nltk
@@ -16,8 +19,9 @@ import gradio as gr
16
  from keras.models import load_model
17
  from keras.preprocessing.sequence import pad_sequences
18
 
19
- # Suppress warnings
20
  warnings.filterwarnings('ignore')
 
21
 
22
  # Constants
23
  MAX_LEN = 100
@@ -29,20 +33,20 @@ nltk.download('stopwords', quiet=True)
29
  # Expand common English contractions
30
  def expand_contractions(text):
31
  contractions = {
32
- "i'm": "i am", "you're": "you are", "he's": "he is",
33
- "she's": "she is", "it's": "it is", "we're": "we are",
34
- "they're": "they are", "i've": "i have", "you've": "you have",
35
- "we've": "we have", "they've": "they have", "i'll": "i will",
36
- "you'll": "you will", "he'll": "he will", "she'll": "she will",
37
- "we'll": "we will", "they'll": "they will", "i'd": "i would",
38
- "you'd": "you would", "he'd": "he would", "she'd": "she would",
39
- "we'd": "we would", "they'd": "they would", "don't": "do not",
40
- "doesn't": "does not", "didn't": "did not", "can't": "cannot",
41
- "couldn't": "could not", "won't": "will not", "wouldn't": "would not",
42
- "shouldn't": "should not", "isn't": "is not", "aren't": "are not",
43
- "wasn't": "was not", "weren't": "were not", "hasn't": "has not",
44
- "haven't": "have not", "hadn't": "had not", "mightn't": "might not",
45
- "mustn't": "must not", "needn't": "need not", "shan't": "shall not"
46
  }
47
  for contraction, expansion in contractions.items():
48
  text = re.sub(r'\b' + contraction + r'\b', expansion, text, flags=re.IGNORECASE)
@@ -50,7 +54,6 @@ def expand_contractions(text):
50
 
51
  # Preprocessing Function
52
  def preprocess(text):
53
- # Define words to keep
54
  negations = {"not", "no", "nor", "never", "n't", "nobody", "nothing", "neither", "nowhere", "none"}
55
  important_words = {"am", "is", "are", "was", "were", "be", "been", "being"}
56
 
@@ -58,22 +61,12 @@ def preprocess(text):
58
  from nltk.corpus import stopwords
59
  stop_words = set(stopwords.words("english")) - negations - important_words
60
  except:
61
- # Fallback if NLTK not available
62
  stop_words = set()
63
 
64
- # Convert to lowercase
65
  text = text.lower()
66
-
67
- # Expand contractions
68
  text = expand_contractions(text)
69
-
70
- # Remove digits
71
  text = re.sub(r"\d+", "", text)
72
-
73
- # Remove punctuation
74
  text = text.translate(str.maketrans('', '', string.punctuation))
75
-
76
- # Remove stopwords while keeping negations and important words
77
  words = [w for w in text.split() if w not in stop_words or w in negations or w in important_words]
78
 
79
  return " ".join(words)
@@ -81,11 +74,9 @@ def preprocess(text):
81
  # Load Train Model and Tokenizer
82
  def load_resources():
83
  try:
84
- # Load model
85
  model = load_model(MODEL_PATH)
86
  print(f"βœ“ Model loaded successfully from {MODEL_PATH}")
87
 
88
- # Load Tokenizer
89
  with open(TOKENIZER_PATH, "rb") as f:
90
  tokenizer = pickle.load(f)
91
  print(f"βœ“ Tokenizer loaded successfully from {TOKENIZER_PATH}")
@@ -104,32 +95,25 @@ model, tokenizer = load_resources()
104
 
105
  # Prediction Function
106
  def predict_sentiment(text):
107
- # Validate input
108
  if not text or not text.strip():
109
  return "⚠️ Neutral", "33.33%", "Please enter some text to analyze!"
110
 
111
- # Preprocess text
112
  processed_text = preprocess(text)
113
 
114
- # Check if text is empty after preprocessing
115
  if not processed_text.strip():
116
  return "⚠️ Neutral", "33.33%", "Text is empty after preprocessing. Try adding more words."
117
 
118
- # Tokenize and pad
119
  seq = tokenizer.texts_to_sequences([processed_text])
120
  padded = pad_sequences(seq, maxlen=MAX_LEN, padding='post')
121
 
122
- # Predict
123
  pred = model.predict(padded, verbose=0)
124
  label_idx = np.argmax(pred, axis=1)[0]
125
  confidence = pred[0][label_idx]
126
 
127
- # Map to label with emoji
128
  labels = ["😞 Negative", "😊 Positive", "😐 Neutral"]
129
  sentiment = labels[label_idx]
130
  confidence_percentage = f"{confidence * 100:.2f}%"
131
 
132
- # Create detailed results
133
  detailed_results = f"""
134
  ### πŸ“Š Detailed Analysis:
135
 
@@ -151,7 +135,6 @@ def predict_sentiment(text):
151
  def create_gradio_interface():
152
  """Create and configure Gradio interface"""
153
 
154
- # Example texts for quick testing
155
  examples = [
156
  ["I'm so happy with my purchase! Highly recommended!"],
157
  ["I don't like this at all. Very disappointing."],
@@ -174,9 +157,7 @@ def create_gradio_interface():
174
  ["I'm okay"]
175
  ]
176
 
177
- # Create interface
178
  with gr.Blocks(title="Sentiment Analysis") as interface:
179
- # Header
180
  gr.Markdown("""
181
  # 🎭 Sentiment Analysis - AI Powered
182
  ### Analyze the sentiment of your text using Deep Learning (LSTM Model)
@@ -184,10 +165,8 @@ def create_gradio_interface():
184
  **Instructions:** Enter any text in English and the model will predict whether it's Positive, Negative, or Neutral.
185
  """)
186
 
187
- # Main interface
188
  with gr.Row():
189
  with gr.Column(scale=1):
190
- # Input
191
  text_input = gr.Textbox(
192
  label="πŸ“ Enter Your Text",
193
  placeholder="Type your text here... (e.g., 'I love this product!')",
@@ -195,13 +174,11 @@ def create_gradio_interface():
195
  max_lines=10
196
  )
197
 
198
- # Buttons
199
  with gr.Row():
200
  analyze_btn = gr.Button("πŸ” Analyze Sentiment", variant="primary", size="lg")
201
  clear_btn = gr.ClearButton([text_input], value="πŸ—‘οΈ Clear", size="lg")
202
 
203
  with gr.Column(scale=1):
204
- # Outputs
205
  sentiment_output = gr.Textbox(
206
  label="🎯 Predicted Sentiment",
207
  interactive=False
@@ -211,13 +188,11 @@ def create_gradio_interface():
211
  interactive=False
212
  )
213
 
214
- # Detailed results
215
  detailed_output = gr.Markdown(
216
  label="πŸ“Š Detailed Analysis",
217
  value="Results will appear here after analysis..."
218
  )
219
 
220
- # Examples
221
  gr.Markdown("### πŸ’‘ Try These Examples:")
222
  gr.Examples(
223
  examples=examples,
@@ -227,7 +202,6 @@ def create_gradio_interface():
227
  cache_examples=False
228
  )
229
 
230
- # Footer info
231
  gr.Markdown("""
232
  ---
233
  **Model Information:**
@@ -241,14 +215,12 @@ def create_gradio_interface():
241
  - Longer texts provide more context for accurate predictions
242
  """)
243
 
244
- # Connect button to function
245
  analyze_btn.click(
246
  fn=predict_sentiment,
247
  inputs=text_input,
248
  outputs=[sentiment_output, confidence_output, detailed_output]
249
  )
250
 
251
- # Also trigger on Enter key
252
  text_input.submit(
253
  fn=predict_sentiment,
254
  inputs=text_input,
@@ -257,6 +229,16 @@ def create_gradio_interface():
257
 
258
  return interface
259
 
 
 
 
 
 
 
 
 
 
 
260
  # MAIN EXECUTION
261
  if __name__ == "__main__":
262
  print("\n" + "=" * 70)
@@ -266,19 +248,25 @@ if __name__ == "__main__":
266
  # Create interface
267
  interface = create_gradio_interface()
268
 
269
- # Launch with configuration
270
- interface.launch(
271
- server_name="0.0.0.0",
272
- server_port=7860,
273
- share=False,
274
- show_error=True,
275
- ssr_mode=False,
276
- theme=gr.themes.Soft(),
277
- quiet=True # Suppress server messages
278
- )
 
 
 
 
 
279
 
280
  print("\n" + "=" * 70)
281
- print("βœ“ Interface is running!")
282
- print(" Local URL: http://localhost:7860")
283
- print(" Press Ctrl+C to stop the server")
 
284
  print("=" * 70)
 
1
  # Importing Libraries
2
  import os
3
+ import sys
4
+ import io
5
+ os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
6
  os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
7
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
8
+ os.environ['GRADIO_HOT_RELOAD'] = 'false'
9
  os.environ['WRAPT_DISABLE_EXTENSIONS'] = 'true'
10
+ os.environ['PYTHONWARNINGS'] = 'ignore'
11
 
12
  import re
13
  import nltk
 
19
  from keras.models import load_model
20
  from keras.preprocessing.sequence import pad_sequences
21
 
22
+ # Suppress all warnings
23
  warnings.filterwarnings('ignore')
24
+ warnings.simplefilter('ignore')
25
 
26
  # Constants
27
  MAX_LEN = 100
 
33
  # Expand common English contractions
34
  def expand_contractions(text):
35
  contractions = {
36
+ "i'm": "i am", "you're": "you are", "he's": "he is",
37
+ "she's": "she is", "it's": "it is", "we're": "we are",
38
+ "they're": "they are", "i've": "i have", "you've": "you have",
39
+ "we've": "we have", "they've": "they have", "i'll": "i will",
40
+ "you'll": "you will", "he'll": "he will", "she'll": "she will",
41
+ "we'll": "we will", "they'll": "they will", "i'd": "i would",
42
+ "you'd": "you would", "he'd": "he would", "she'd": "she would",
43
+ "we'd": "we would", "they'd": "they would", "don't": "do not",
44
+ "doesn't": "does not", "didn't": "did not", "can't": "cannot",
45
+ "couldn't": "could not", "won't": "will not", "wouldn't": "would not",
46
+ "shouldn't": "should not", "isn't": "is not", "aren't": "are not",
47
+ "wasn't": "was not", "weren't": "were not", "hasn't": "has not",
48
+ "haven't": "have not", "hadn't": "had not", "mightn't": "might not",
49
+ "mustn't": "must not", "needn't": "need not", "shan't": "shall not"
50
  }
51
  for contraction, expansion in contractions.items():
52
  text = re.sub(r'\b' + contraction + r'\b', expansion, text, flags=re.IGNORECASE)
 
54
 
55
  # Preprocessing Function
56
  def preprocess(text):
 
57
  negations = {"not", "no", "nor", "never", "n't", "nobody", "nothing", "neither", "nowhere", "none"}
58
  important_words = {"am", "is", "are", "was", "were", "be", "been", "being"}
59
 
 
61
  from nltk.corpus import stopwords
62
  stop_words = set(stopwords.words("english")) - negations - important_words
63
  except:
 
64
  stop_words = set()
65
 
 
66
  text = text.lower()
 
 
67
  text = expand_contractions(text)
 
 
68
  text = re.sub(r"\d+", "", text)
 
 
69
  text = text.translate(str.maketrans('', '', string.punctuation))
 
 
70
  words = [w for w in text.split() if w not in stop_words or w in negations or w in important_words]
71
 
72
  return " ".join(words)
 
74
  # Load Train Model and Tokenizer
75
  def load_resources():
76
  try:
 
77
  model = load_model(MODEL_PATH)
78
  print(f"βœ“ Model loaded successfully from {MODEL_PATH}")
79
 
 
80
  with open(TOKENIZER_PATH, "rb") as f:
81
  tokenizer = pickle.load(f)
82
  print(f"βœ“ Tokenizer loaded successfully from {TOKENIZER_PATH}")
 
95
 
96
  # Prediction Function
97
  def predict_sentiment(text):
 
98
  if not text or not text.strip():
99
  return "⚠️ Neutral", "33.33%", "Please enter some text to analyze!"
100
 
 
101
  processed_text = preprocess(text)
102
 
 
103
  if not processed_text.strip():
104
  return "⚠️ Neutral", "33.33%", "Text is empty after preprocessing. Try adding more words."
105
 
 
106
  seq = tokenizer.texts_to_sequences([processed_text])
107
  padded = pad_sequences(seq, maxlen=MAX_LEN, padding='post')
108
 
 
109
  pred = model.predict(padded, verbose=0)
110
  label_idx = np.argmax(pred, axis=1)[0]
111
  confidence = pred[0][label_idx]
112
 
 
113
  labels = ["😞 Negative", "😊 Positive", "😐 Neutral"]
114
  sentiment = labels[label_idx]
115
  confidence_percentage = f"{confidence * 100:.2f}%"
116
 
 
117
  detailed_results = f"""
118
  ### πŸ“Š Detailed Analysis:
119
 
 
135
  def create_gradio_interface():
136
  """Create and configure Gradio interface"""
137
 
 
138
  examples = [
139
  ["I'm so happy with my purchase! Highly recommended!"],
140
  ["I don't like this at all. Very disappointing."],
 
157
  ["I'm okay"]
158
  ]
159
 
 
160
  with gr.Blocks(title="Sentiment Analysis") as interface:
 
161
  gr.Markdown("""
162
  # 🎭 Sentiment Analysis - AI Powered
163
  ### Analyze the sentiment of your text using Deep Learning (LSTM Model)
 
165
  **Instructions:** Enter any text in English and the model will predict whether it's Positive, Negative, or Neutral.
166
  """)
167
 
 
168
  with gr.Row():
169
  with gr.Column(scale=1):
 
170
  text_input = gr.Textbox(
171
  label="πŸ“ Enter Your Text",
172
  placeholder="Type your text here... (e.g., 'I love this product!')",
 
174
  max_lines=10
175
  )
176
 
 
177
  with gr.Row():
178
  analyze_btn = gr.Button("πŸ” Analyze Sentiment", variant="primary", size="lg")
179
  clear_btn = gr.ClearButton([text_input], value="πŸ—‘οΈ Clear", size="lg")
180
 
181
  with gr.Column(scale=1):
 
182
  sentiment_output = gr.Textbox(
183
  label="🎯 Predicted Sentiment",
184
  interactive=False
 
188
  interactive=False
189
  )
190
 
 
191
  detailed_output = gr.Markdown(
192
  label="πŸ“Š Detailed Analysis",
193
  value="Results will appear here after analysis..."
194
  )
195
 
 
196
  gr.Markdown("### πŸ’‘ Try These Examples:")
197
  gr.Examples(
198
  examples=examples,
 
202
  cache_examples=False
203
  )
204
 
 
205
  gr.Markdown("""
206
  ---
207
  **Model Information:**
 
215
  - Longer texts provide more context for accurate predictions
216
  """)
217
 
 
218
  analyze_btn.click(
219
  fn=predict_sentiment,
220
  inputs=text_input,
221
  outputs=[sentiment_output, confidence_output, detailed_output]
222
  )
223
 
 
224
  text_input.submit(
225
  fn=predict_sentiment,
226
  inputs=text_input,
 
229
 
230
  return interface
231
 
232
+ # Context manager to suppress stderr temporarily
233
+ class SuppressStderr:
234
+ def __enter__(self):
235
+ self.original_stderr = sys.stderr
236
+ sys.stderr = io.StringIO()
237
+ return self
238
+
239
+ def __exit__(self, exc_type, exc_val, exc_tb):
240
+ sys.stderr = self.original_stderr
241
+
242
  # MAIN EXECUTION
243
  if __name__ == "__main__":
244
  print("\n" + "=" * 70)
 
248
  # Create interface
249
  interface = create_gradio_interface()
250
 
251
+ # Launch with stderr suppression to hide asyncio warnings
252
+ print("⏳ Launching server...")
253
+
254
+ with SuppressStderr():
255
+ # Launch configuration
256
+ interface.launch(
257
+ server_name="0.0.0.0",
258
+ server_port=7860,
259
+ share=False,
260
+ show_error=True,
261
+ ssr_mode=False,
262
+ theme=gr.themes.Soft(),
263
+ quiet=False,
264
+ prevent_thread_lock=False
265
+ )
266
 
267
  print("\n" + "=" * 70)
268
+ print("βœ… Interface is LIVE and ready to use!")
269
+ print(" 🌐 Local URL: http://localhost:7860")
270
+ print(" ⚑ Server is running smoothly")
271
+ print(" πŸ›‘ Press Ctrl+C to stop")
272
  print("=" * 70)