Update app.py
Browse files
app.py
CHANGED
|
@@ -1,136 +1,215 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
#
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pickle
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import nltk
|
| 6 |
+
from nltk.corpus import stopwords
|
| 7 |
+
from nltk.stem import WordNetLemmatizer
|
| 8 |
+
import re
|
| 9 |
+
import warnings
|
| 10 |
+
warnings.filterwarnings('ignore')
|
| 11 |
+
|
| 12 |
+
# Download NLTK data
|
| 13 |
+
print("Downloading NLTK resources...")
|
| 14 |
+
nltk.download('stopwords', quiet=True)
|
| 15 |
+
nltk.download('wordnet', quiet=True)
|
| 16 |
+
nltk.download('omw-1.4', quiet=True)
|
| 17 |
+
nltk.download('punkt', quiet=True)
|
| 18 |
+
print("β
NLTK resources downloaded")
|
| 19 |
+
|
| 20 |
+
# Load models
|
| 21 |
+
print("Loading models...")
|
| 22 |
+
try:
|
| 23 |
+
with open('best_model.pkl', 'rb') as f:
|
| 24 |
+
model = pickle.load(f)
|
| 25 |
+
print("β
Model loaded")
|
| 26 |
+
|
| 27 |
+
with open('tfidf_vectorizer.pkl', 'rb') as f:
|
| 28 |
+
vectorizer = pickle.load(f)
|
| 29 |
+
print("β
Vectorizer loaded")
|
| 30 |
+
|
| 31 |
+
with open('preprocessor.pkl', 'rb') as f:
|
| 32 |
+
preprocessor = pickle.load(f)
|
| 33 |
+
print("β
Preprocessor loaded")
|
| 34 |
+
|
| 35 |
+
except Exception as e:
|
| 36 |
+
print(f"β Error loading models: {e}")
|
| 37 |
+
raise
|
| 38 |
+
|
| 39 |
+
# Feature extraction function
|
| 40 |
+
def extract_features(texts, original_texts):
|
| 41 |
+
"""Extract statistical features from texts."""
|
| 42 |
+
features = {
|
| 43 |
+
'review_length': [len(text) for text in original_texts],
|
| 44 |
+
'word_count': [len(text.split()) for text in texts],
|
| 45 |
+
'avg_word_length': [
|
| 46 |
+
np.mean([len(word) for word in text.split()]) if text else 0
|
| 47 |
+
for text in texts
|
| 48 |
+
],
|
| 49 |
+
'exclamation_count': [text.count('!') for text in original_texts],
|
| 50 |
+
'question_count': [text.count('?') for text in original_texts],
|
| 51 |
+
'capital_ratio': [
|
| 52 |
+
sum(1 for c in text if c.isupper()) / len(text) if len(text) > 0 else 0
|
| 53 |
+
for text in original_texts
|
| 54 |
+
]
|
| 55 |
+
}
|
| 56 |
+
return pd.DataFrame(features)
|
| 57 |
+
|
| 58 |
+
# Prediction function
|
| 59 |
+
def predict_sentiment(review_text):
|
| 60 |
+
"""Predict sentiment for a review."""
|
| 61 |
+
if not review_text or not review_text.strip():
|
| 62 |
+
return "β οΈ Please enter a review!", "", "", "", ""
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
# Preprocess
|
| 66 |
+
cleaned = preprocessor.clean_text(review_text)
|
| 67 |
+
|
| 68 |
+
# Vectorize
|
| 69 |
+
vectorized = vectorizer.transform([cleaned]).toarray()
|
| 70 |
+
|
| 71 |
+
# Extract additional features
|
| 72 |
+
add_features = extract_features([cleaned], [review_text])
|
| 73 |
+
|
| 74 |
+
# Combine features
|
| 75 |
+
X_new = np.concatenate([vectorized, add_features.values], axis=1)
|
| 76 |
+
|
| 77 |
+
# Predict
|
| 78 |
+
prediction = model.predict(X_new)[0]
|
| 79 |
+
|
| 80 |
+
# Get probabilities if available
|
| 81 |
+
if hasattr(model, 'predict_proba'):
|
| 82 |
+
proba = model.predict_proba(X_new)[0]
|
| 83 |
+
confidence = max(proba)
|
| 84 |
+
prob_neg = proba[0]
|
| 85 |
+
prob_pos = proba[1]
|
| 86 |
+
else:
|
| 87 |
+
confidence = None
|
| 88 |
+
prob_neg = None
|
| 89 |
+
prob_pos = None
|
| 90 |
+
|
| 91 |
+
# Format output
|
| 92 |
+
sentiment = "β
Positive π" if prediction == 1 else "β Negative π"
|
| 93 |
+
conf_str = f"{confidence:.2%}" if confidence else "N/A"
|
| 94 |
+
neg_str = f"{prob_neg:.2%}" if prob_neg else "N/A"
|
| 95 |
+
pos_str = f"{prob_pos:.2%}" if prob_pos else "N/A"
|
| 96 |
+
|
| 97 |
+
return sentiment, conf_str, neg_str, pos_str, cleaned
|
| 98 |
+
|
| 99 |
+
except Exception as e:
|
| 100 |
+
return f"β Error: {str(e)}", "", "", "", ""
|
| 101 |
+
|
| 102 |
+
# Create Gradio interface
|
| 103 |
+
print("Creating Gradio interface...")
|
| 104 |
+
|
| 105 |
+
with gr.Blocks(
|
| 106 |
+
theme=gr.themes.Soft(),
|
| 107 |
+
title="Restaurant Review Sentiment Analyzer",
|
| 108 |
+
css="""
|
| 109 |
+
.gradio-container {font-family: 'Arial', sans-serif;}
|
| 110 |
+
"""
|
| 111 |
+
) as demo:
|
| 112 |
+
|
| 113 |
+
gr.Markdown("""
|
| 114 |
+
# π½οΈ Restaurant Review Sentiment Analyzer
|
| 115 |
+
### AI-Powered Sentiment Analysis with Machine Learning
|
| 116 |
+
|
| 117 |
+
Enter a restaurant review to analyze its sentiment in real-time!
|
| 118 |
+
|
| 119 |
+
**Model:** Random Forest Classifier
|
| 120 |
+
**Accuracy:** 85%+
|
| 121 |
+
**Features:** TF-IDF + Statistical Text Features
|
| 122 |
+
""")
|
| 123 |
+
|
| 124 |
+
with gr.Row():
|
| 125 |
+
with gr.Column(scale=2):
|
| 126 |
+
gr.Markdown("### π Enter Your Review")
|
| 127 |
+
input_text = gr.Textbox(
|
| 128 |
+
label="Restaurant Review",
|
| 129 |
+
placeholder="e.g., The food was amazing and the service was excellent!",
|
| 130 |
+
lines=6,
|
| 131 |
+
max_lines=10
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
with gr.Row():
|
| 135 |
+
submit_btn = gr.Button("π Analyze Sentiment", variant="primary", size="lg")
|
| 136 |
+
clear_btn = gr.ClearButton([input_text], value="ποΈ Clear", size="lg")
|
| 137 |
+
|
| 138 |
+
with gr.Column(scale=2):
|
| 139 |
+
gr.Markdown("### π Analysis Results")
|
| 140 |
+
sentiment_output = gr.Textbox(label="π― Predicted Sentiment", interactive=False)
|
| 141 |
+
confidence_output = gr.Textbox(label="π Confidence Score", interactive=False)
|
| 142 |
+
|
| 143 |
+
with gr.Row():
|
| 144 |
+
neg_prob = gr.Textbox(label="π Negative Probability", interactive=False)
|
| 145 |
+
pos_prob = gr.Textbox(label="π Positive Probability", interactive=False)
|
| 146 |
+
|
| 147 |
+
with gr.Accordion("π Preprocessing Details", open=False):
|
| 148 |
+
cleaned_output = gr.Textbox(
|
| 149 |
+
label="Cleaned Review Text (After Preprocessing)",
|
| 150 |
+
interactive=False,
|
| 151 |
+
lines=3
|
| 152 |
+
)
|
| 153 |
+
gr.Markdown("""
|
| 154 |
+
**Preprocessing Steps Applied:**
|
| 155 |
+
1. Convert to lowercase
|
| 156 |
+
2. Remove special characters and numbers
|
| 157 |
+
3. Remove stopwords (preserving negations)
|
| 158 |
+
4. Apply lemmatization
|
| 159 |
+
5. Extract statistical features
|
| 160 |
+
""")
|
| 161 |
+
|
| 162 |
+
gr.Markdown("---")
|
| 163 |
+
gr.Markdown("### π‘ Try These Example Reviews")
|
| 164 |
+
|
| 165 |
+
gr.Examples(
|
| 166 |
+
examples=[
|
| 167 |
+
["The food was absolutely amazing! Best restaurant I've ever been to! The service was impeccable."],
|
| 168 |
+
["Terrible service and the food was cold. The waiter was rude. Never coming back!"],
|
| 169 |
+
["Outstanding experience from start to finish! Every dish was cooked to perfection. Highly recommended!"],
|
| 170 |
+
["Worst meal I've ever had. Complete waste of money. Very disappointing experience."],
|
| 171 |
+
["Good food but the portions were quite small. Reasonable prices. Service was okay."],
|
| 172 |
+
["Fantastic! The ambiance was perfect and the food was delicious. Will definitely return!"],
|
| 173 |
+
["Not impressed at all. The quality has really gone downhill. Won't be going back."],
|
| 174 |
+
["Absolutely loved everything! Great variety and excellent presentation. Five stars!"]
|
| 175 |
+
],
|
| 176 |
+
inputs=input_text,
|
| 177 |
+
label="Click any example to try it"
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
gr.Markdown("""
|
| 181 |
+
---
|
| 182 |
+
### π About This Model
|
| 183 |
+
|
| 184 |
+
**Machine Learning Pipeline:**
|
| 185 |
+
- **Preprocessing:** Lemmatization, stopword removal, text cleaning
|
| 186 |
+
- **Feature Engineering:** TF-IDF vectorization (1500 features, bigrams) + 6 statistical features
|
| 187 |
+
- **Algorithm:** Random Forest Classifier
|
| 188 |
+
- **Training:** 6 different models compared, best one deployed
|
| 189 |
+
- **Evaluation:** Cross-validation, multiple metrics (Accuracy, F1, ROC-AUC)
|
| 190 |
+
|
| 191 |
+
**Technologies Used:**
|
| 192 |
+
- Python, Scikit-learn, NLTK, Gradio, Pandas, NumPy
|
| 193 |
+
|
| 194 |
+
**Developer:** Einstein Ellandala | Project: ML-06-BML11
|
| 195 |
+
|
| 196 |
+
π **Full Project:** [View on GitHub](https://github.com/MrEinsteinE/sentiment-analysis-restaurant)
|
| 197 |
+
""")
|
| 198 |
+
|
| 199 |
+
# Connect button to prediction function
|
| 200 |
+
submit_btn.click(
|
| 201 |
+
fn=predict_sentiment,
|
| 202 |
+
inputs=input_text,
|
| 203 |
+
outputs=[sentiment_output, confidence_output, neg_prob, pos_prob, cleaned_output]
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
print("β
Gradio interface created")
|
| 207 |
+
print("π Launching application...")
|
| 208 |
+
|
| 209 |
+
# Launch the app
|
| 210 |
+
if __name__ == "__main__":
|
| 211 |
+
demo.launch(
|
| 212 |
+
server_name="0.0.0.0",
|
| 213 |
+
server_port=7860,
|
| 214 |
+
show_error=True
|
| 215 |
+
)
|