Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
# Importing Libraries
|
| 2 |
-
import os
|
|
|
|
| 3 |
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
| 4 |
-
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '
|
| 5 |
-
os.environ['
|
| 6 |
-
|
| 7 |
import re
|
| 8 |
import nltk
|
| 9 |
import pickle
|
|
@@ -13,7 +14,6 @@ import gradio as gr
|
|
| 13 |
from keras.models import load_model
|
| 14 |
from keras.preprocessing.sequence import pad_sequences
|
| 15 |
|
| 16 |
-
|
| 17 |
# Constants
|
| 18 |
MAX_LEN = 100
|
| 19 |
MODEL_PATH = "sentiment_analysis_best.keras"
|
|
@@ -25,25 +25,51 @@ nltk.download('stopwords', quiet=True)
|
|
| 25 |
def expand_contractions(text):
|
| 26 |
"""Expand common English contractions"""
|
| 27 |
contractions = {
|
| 28 |
-
"i'm": "i am",
|
| 29 |
-
"
|
| 30 |
-
"
|
| 31 |
-
"
|
| 32 |
-
"
|
| 33 |
-
"we'
|
| 34 |
-
"
|
| 35 |
-
"
|
| 36 |
-
"
|
| 37 |
-
"
|
| 38 |
-
"
|
| 39 |
-
"
|
| 40 |
-
"
|
| 41 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
}
|
| 43 |
-
|
| 44 |
for contraction, expansion in contractions.items():
|
| 45 |
text = re.sub(r'\b' + contraction + r'\b', expansion, text, flags=re.IGNORECASE)
|
| 46 |
-
|
| 47 |
return text
|
| 48 |
|
| 49 |
# Preprocessing Function
|
|
@@ -58,22 +84,22 @@ def preprocess(text):
|
|
| 58 |
except:
|
| 59 |
# Fallback if NLTK not available
|
| 60 |
stop_words = set()
|
| 61 |
-
|
| 62 |
# Convert to lowercase
|
| 63 |
text = text.lower()
|
| 64 |
-
|
| 65 |
# Expand contractions
|
| 66 |
text = expand_contractions(text)
|
| 67 |
-
|
| 68 |
# Remove digits
|
| 69 |
text = re.sub(r"\d+", "", text)
|
| 70 |
-
|
| 71 |
# Remove punctuation
|
| 72 |
text = text.translate(str.maketrans('', '', string.punctuation))
|
| 73 |
-
|
| 74 |
# Remove stopwords while keeping negations and important words
|
| 75 |
words = [w for w in text.split() if w not in stop_words or w in negations or w in important_words]
|
| 76 |
-
|
| 77 |
return " ".join(words)
|
| 78 |
|
| 79 |
# Load Train Model and Tokenizer
|
|
@@ -82,17 +108,16 @@ def load_resources():
|
|
| 82 |
# Load model
|
| 83 |
model = load_model(MODEL_PATH)
|
| 84 |
print(f"β Model loaded successfully from {MODEL_PATH}")
|
| 85 |
-
|
| 86 |
# Load Tokenizer
|
| 87 |
with open(TOKENIZER_PATH, "rb") as f:
|
| 88 |
tokenizer = pickle.load(f)
|
| 89 |
print(f"β Tokenizer loaded successfully from {TOKENIZER_PATH}")
|
| 90 |
-
|
| 91 |
return model, tokenizer
|
| 92 |
-
|
| 93 |
except FileNotFoundError as e:
|
| 94 |
print(f"β Error: Model or Tokenizer file not found!")
|
| 95 |
-
print(f"
|
| 96 |
raise e
|
| 97 |
except Exception as e:
|
| 98 |
print(f"β Error loading resources: {e}")
|
|
@@ -131,23 +156,17 @@ def predict_sentiment(text):
|
|
| 131 |
# Create detailed results
|
| 132 |
detailed_results = f"""
|
| 133 |
### π Detailed Analysis:
|
| 134 |
-
|
| 135 |
**Original Text:** {text}
|
| 136 |
-
|
| 137 |
**Processed Text:** {processed_text}
|
| 138 |
-
|
| 139 |
**Prediction Probabilities:**
|
| 140 |
- π Negative: {pred[0][0] * 100:.2f}%
|
| 141 |
- π Positive: {pred[0][1] * 100:.2f}%
|
| 142 |
- π Neutral: {pred[0][2] * 100:.2f}%
|
| 143 |
-
|
| 144 |
**Final Sentiment:** {sentiment}
|
| 145 |
**Confidence:** {confidence_percentage}
|
| 146 |
"""
|
| 147 |
-
|
| 148 |
return sentiment, confidence_percentage, detailed_results
|
| 149 |
|
| 150 |
-
|
| 151 |
# GRADIO INTERFACE
|
| 152 |
def create_gradio_interface():
|
| 153 |
"""Create and configure Gradio interface"""
|
|
@@ -177,7 +196,6 @@ def create_gradio_interface():
|
|
| 177 |
|
| 178 |
# Create interface - theme removed to avoid Gradio 6.0 warning
|
| 179 |
with gr.Blocks(title="Sentiment Analysis") as interface:
|
| 180 |
-
|
| 181 |
# Header
|
| 182 |
gr.Markdown("""
|
| 183 |
# π Sentiment Analysis - AI Powered
|
|
@@ -259,7 +277,6 @@ def create_gradio_interface():
|
|
| 259 |
|
| 260 |
return interface
|
| 261 |
|
| 262 |
-
|
| 263 |
# MAIN EXECUTION
|
| 264 |
if __name__ == "__main__":
|
| 265 |
print("\n" + "=" * 70)
|
|
@@ -270,18 +287,16 @@ if __name__ == "__main__":
|
|
| 270 |
interface = create_gradio_interface()
|
| 271 |
|
| 272 |
# Launch with configuration - theme moved here for Gradio 6.0+
|
| 273 |
-
# ssr_mode=False disables server-side rendering and the hot reload issue
|
| 274 |
interface.launch(
|
| 275 |
server_name="0.0.0.0",
|
| 276 |
server_port=7860,
|
| 277 |
share=False,
|
| 278 |
show_error=True,
|
| 279 |
-
ssr_mode=False, # This disables SSR and prevents the hot reload error
|
| 280 |
theme=gr.themes.Soft()
|
| 281 |
)
|
| 282 |
|
| 283 |
print("\n" + "=" * 70)
|
| 284 |
print("β Interface is running!")
|
| 285 |
-
print("
|
| 286 |
-
print("
|
| 287 |
print("=" * 70)
|
|
|
|
| 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 to avoid the error
|
| 7 |
+
# You have no Nvidia GPU and Cuda
|
| 8 |
import re
|
| 9 |
import nltk
|
| 10 |
import pickle
|
|
|
|
| 14 |
from keras.models import load_model
|
| 15 |
from keras.preprocessing.sequence import pad_sequences
|
| 16 |
|
|
|
|
| 17 |
# Constants
|
| 18 |
MAX_LEN = 100
|
| 19 |
MODEL_PATH = "sentiment_analysis_best.keras"
|
|
|
|
| 25 |
def expand_contractions(text):
|
| 26 |
"""Expand common English contractions"""
|
| 27 |
contractions = {
|
| 28 |
+
"i'm": "i am",
|
| 29 |
+
"you're": "you are",
|
| 30 |
+
"he's": "he is",
|
| 31 |
+
"she's": "she is",
|
| 32 |
+
"it's": "it is",
|
| 33 |
+
"we're": "we are",
|
| 34 |
+
"they're": "they are",
|
| 35 |
+
"i've": "i have",
|
| 36 |
+
"you've": "you have",
|
| 37 |
+
"we've": "we have",
|
| 38 |
+
"they've": "they have",
|
| 39 |
+
"i'll": "i will",
|
| 40 |
+
"you'll": "you will",
|
| 41 |
+
"he'll": "he will",
|
| 42 |
+
"she'll": "she will",
|
| 43 |
+
"we'll": "we will",
|
| 44 |
+
"they'll": "they will",
|
| 45 |
+
"i'd": "i would",
|
| 46 |
+
"you'd": "you would",
|
| 47 |
+
"he'd": "he would",
|
| 48 |
+
"she'd": "she would",
|
| 49 |
+
"we'd": "we would",
|
| 50 |
+
"they'd": "they would",
|
| 51 |
+
"don't": "do not",
|
| 52 |
+
"doesn't": "does not",
|
| 53 |
+
"didn't": "did not",
|
| 54 |
+
"can't": "cannot",
|
| 55 |
+
"couldn't": "could not",
|
| 56 |
+
"won't": "will not",
|
| 57 |
+
"wouldn't": "would not",
|
| 58 |
+
"shouldn't": "should not",
|
| 59 |
+
"isn't": "is not",
|
| 60 |
+
"aren't": "are not",
|
| 61 |
+
"wasn't": "was not",
|
| 62 |
+
"weren't": "were not",
|
| 63 |
+
"hasn't": "has not",
|
| 64 |
+
"haven't": "have not",
|
| 65 |
+
"hadn't": "had not",
|
| 66 |
+
"mightn't": "might not",
|
| 67 |
+
"mustn't": "must not",
|
| 68 |
+
"needn't": "need not",
|
| 69 |
+
"shan't": "shall not"
|
| 70 |
}
|
|
|
|
| 71 |
for contraction, expansion in contractions.items():
|
| 72 |
text = re.sub(r'\b' + contraction + r'\b', expansion, text, flags=re.IGNORECASE)
|
|
|
|
| 73 |
return text
|
| 74 |
|
| 75 |
# Preprocessing Function
|
|
|
|
| 84 |
except:
|
| 85 |
# Fallback if NLTK not available
|
| 86 |
stop_words = set()
|
| 87 |
+
|
| 88 |
# Convert to lowercase
|
| 89 |
text = text.lower()
|
| 90 |
+
|
| 91 |
# Expand contractions
|
| 92 |
text = expand_contractions(text)
|
| 93 |
+
|
| 94 |
# Remove digits
|
| 95 |
text = re.sub(r"\d+", "", text)
|
| 96 |
+
|
| 97 |
# Remove punctuation
|
| 98 |
text = text.translate(str.maketrans('', '', string.punctuation))
|
| 99 |
+
|
| 100 |
# Remove stopwords while keeping negations and important words
|
| 101 |
words = [w for w in text.split() if w not in stop_words or w in negations or w in important_words]
|
| 102 |
+
|
| 103 |
return " ".join(words)
|
| 104 |
|
| 105 |
# Load Train Model and Tokenizer
|
|
|
|
| 108 |
# Load model
|
| 109 |
model = load_model(MODEL_PATH)
|
| 110 |
print(f"β Model loaded successfully from {MODEL_PATH}")
|
| 111 |
+
|
| 112 |
# Load Tokenizer
|
| 113 |
with open(TOKENIZER_PATH, "rb") as f:
|
| 114 |
tokenizer = pickle.load(f)
|
| 115 |
print(f"β Tokenizer loaded successfully from {TOKENIZER_PATH}")
|
| 116 |
+
|
| 117 |
return model, tokenizer
|
|
|
|
| 118 |
except FileNotFoundError as e:
|
| 119 |
print(f"β Error: Model or Tokenizer file not found!")
|
| 120 |
+
print(f" Make sure {MODEL_PATH} AND {TOKENIZER_PATH} are in the same directory.")
|
| 121 |
raise e
|
| 122 |
except Exception as e:
|
| 123 |
print(f"β Error loading resources: {e}")
|
|
|
|
| 156 |
# Create detailed results
|
| 157 |
detailed_results = f"""
|
| 158 |
### π Detailed Analysis:
|
|
|
|
| 159 |
**Original Text:** {text}
|
|
|
|
| 160 |
**Processed Text:** {processed_text}
|
|
|
|
| 161 |
**Prediction Probabilities:**
|
| 162 |
- π Negative: {pred[0][0] * 100:.2f}%
|
| 163 |
- π Positive: {pred[0][1] * 100:.2f}%
|
| 164 |
- π Neutral: {pred[0][2] * 100:.2f}%
|
|
|
|
| 165 |
**Final Sentiment:** {sentiment}
|
| 166 |
**Confidence:** {confidence_percentage}
|
| 167 |
"""
|
|
|
|
| 168 |
return sentiment, confidence_percentage, detailed_results
|
| 169 |
|
|
|
|
| 170 |
# GRADIO INTERFACE
|
| 171 |
def create_gradio_interface():
|
| 172 |
"""Create and configure Gradio interface"""
|
|
|
|
| 196 |
|
| 197 |
# Create interface - theme removed to avoid Gradio 6.0 warning
|
| 198 |
with gr.Blocks(title="Sentiment Analysis") as interface:
|
|
|
|
| 199 |
# Header
|
| 200 |
gr.Markdown("""
|
| 201 |
# π Sentiment Analysis - AI Powered
|
|
|
|
| 277 |
|
| 278 |
return interface
|
| 279 |
|
|
|
|
| 280 |
# MAIN EXECUTION
|
| 281 |
if __name__ == "__main__":
|
| 282 |
print("\n" + "=" * 70)
|
|
|
|
| 287 |
interface = create_gradio_interface()
|
| 288 |
|
| 289 |
# Launch with configuration - theme moved here for Gradio 6.0+
|
|
|
|
| 290 |
interface.launch(
|
| 291 |
server_name="0.0.0.0",
|
| 292 |
server_port=7860,
|
| 293 |
share=False,
|
| 294 |
show_error=True,
|
|
|
|
| 295 |
theme=gr.themes.Soft()
|
| 296 |
)
|
| 297 |
|
| 298 |
print("\n" + "=" * 70)
|
| 299 |
print("β Interface is running!")
|
| 300 |
+
print(" Local URL: http://localhost:7860")
|
| 301 |
+
print(" Press Ctrl+C to stop the server")
|
| 302 |
print("=" * 70)
|