Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,13 @@
|
|
| 1 |
# Importing Libraries
|
| 2 |
import os
|
| 3 |
-
|
|
|
|
|
|
|
| 4 |
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
| 5 |
-
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
| 6 |
-
os.environ['GRADIO_HOT_RELOAD'] = 'false'
|
| 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 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 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
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
print("\n" + "=" * 70)
|
| 281 |
-
print("
|
| 282 |
-
print(" Local URL: http://localhost:7860")
|
| 283 |
-
print("
|
|
|
|
| 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)
|