Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,20 +1,20 @@
|
|
1 |
-
# GRADIO ML CLASSIFICATION APP -
|
2 |
-
#
|
3 |
|
4 |
import gradio as gr
|
5 |
import pandas as pd
|
6 |
import numpy as np
|
7 |
import joblib
|
8 |
import matplotlib.pyplot as plt
|
9 |
-
import seaborn as sns
|
10 |
-
import io
|
11 |
-
import base64
|
12 |
-
from typing import Tuple, List, Optional
|
13 |
import warnings
|
|
|
|
|
|
|
|
|
14 |
warnings.filterwarnings('ignore')
|
15 |
|
16 |
# ============================================================================
|
17 |
-
# MODEL LOADING
|
18 |
# ============================================================================
|
19 |
|
20 |
def load_models():
|
@@ -22,42 +22,39 @@ def load_models():
|
|
22 |
models = {}
|
23 |
|
24 |
try:
|
25 |
-
# Load
|
26 |
try:
|
27 |
models['pipeline'] = joblib.load('models/sentiment_analysis_pipeline.pkl')
|
28 |
models['pipeline_available'] = True
|
29 |
-
except
|
30 |
models['pipeline_available'] = False
|
31 |
|
32 |
-
# Load
|
33 |
try:
|
34 |
models['vectorizer'] = joblib.load('models/tfidf_vectorizer.pkl')
|
35 |
models['vectorizer_available'] = True
|
36 |
-
except
|
37 |
models['vectorizer_available'] = False
|
38 |
|
39 |
-
# Load
|
40 |
try:
|
41 |
models['logistic_regression'] = joblib.load('models/logistic_regression_model.pkl')
|
42 |
models['lr_available'] = True
|
43 |
-
except
|
44 |
models['lr_available'] = False
|
45 |
|
46 |
-
# Load
|
47 |
try:
|
48 |
models['naive_bayes'] = joblib.load('models/multinomial_nb_model.pkl')
|
49 |
models['nb_available'] = True
|
50 |
-
except
|
51 |
models['nb_available'] = False
|
52 |
|
53 |
-
# Check if
|
54 |
pipeline_ready = models['pipeline_available']
|
55 |
individual_ready = models['vectorizer_available'] and (models['lr_available'] or models['nb_available'])
|
56 |
|
57 |
-
if
|
58 |
-
return None
|
59 |
-
|
60 |
-
return models
|
61 |
|
62 |
except Exception as e:
|
63 |
print(f"Error loading models: {e}")
|
@@ -67,93 +64,77 @@ def load_models():
|
|
67 |
MODELS = load_models()
|
68 |
|
69 |
# ============================================================================
|
70 |
-
#
|
71 |
# ============================================================================
|
72 |
|
73 |
-
def
|
74 |
-
"""
|
75 |
if MODELS is None:
|
76 |
-
return
|
|
|
|
|
|
|
|
|
77 |
|
78 |
-
if
|
79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
|
81 |
try:
|
82 |
-
prediction = None
|
83 |
-
probabilities = None
|
84 |
-
|
85 |
if model_choice == "Logistic Regression":
|
86 |
if MODELS.get('pipeline_available'):
|
87 |
-
# Use the complete pipeline (Logistic Regression)
|
88 |
prediction = MODELS['pipeline'].predict([text])[0]
|
89 |
probabilities = MODELS['pipeline'].predict_proba([text])[0]
|
90 |
elif MODELS.get('vectorizer_available') and MODELS.get('lr_available'):
|
91 |
-
# Use individual components
|
92 |
X = MODELS['vectorizer'].transform([text])
|
93 |
prediction = MODELS['logistic_regression'].predict(X)[0]
|
94 |
probabilities = MODELS['logistic_regression'].predict_proba(X)[0]
|
|
|
|
|
95 |
|
96 |
elif model_choice == "Multinomial Naive Bayes":
|
97 |
if MODELS.get('vectorizer_available') and MODELS.get('nb_available'):
|
98 |
-
# Use individual components for NB
|
99 |
X = MODELS['vectorizer'].transform([text])
|
100 |
prediction = MODELS['naive_bayes'].predict(X)[0]
|
101 |
probabilities = MODELS['naive_bayes'].predict_proba(X)[0]
|
|
|
|
|
102 |
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
return prediction_label, probabilities, status
|
109 |
-
else:
|
110 |
-
return None, None, f"❌ Model '{model_choice}' not available!"
|
111 |
|
112 |
except Exception as e:
|
113 |
-
return None, None, f"
|
114 |
-
|
115 |
-
def get_available_models() -> List[str]:
|
116 |
-
"""Get list of available models for selection"""
|
117 |
-
if MODELS is None:
|
118 |
-
return ["No models available"]
|
119 |
-
|
120 |
-
available = []
|
121 |
-
|
122 |
-
if MODELS.get('pipeline_available'):
|
123 |
-
available.append("Logistic Regression")
|
124 |
-
elif MODELS.get('vectorizer_available') and MODELS.get('lr_available'):
|
125 |
-
available.append("Logistic Regression")
|
126 |
-
|
127 |
-
if MODELS.get('vectorizer_available') and MODELS.get('nb_available'):
|
128 |
-
available.append("Multinomial Naive Bayes")
|
129 |
-
|
130 |
-
return available if available else ["No models available"]
|
131 |
|
132 |
-
def
|
133 |
-
"""Create
|
134 |
fig, ax = plt.subplots(figsize=(8, 5))
|
135 |
|
136 |
-
classes = ['Negative
|
137 |
colors = ['#ff6b6b', '#51cf66']
|
138 |
|
139 |
-
bars = ax.bar(classes, probabilities, color=colors, alpha=0.8
|
140 |
|
141 |
-
# Add
|
142 |
for bar, prob in zip(bars, probabilities):
|
143 |
height = bar.get_height()
|
144 |
ax.text(bar.get_x() + bar.get_width()/2., height + 0.01,
|
145 |
-
f'{prob:.1%}', ha='center', va='bottom', fontweight='bold'
|
146 |
|
147 |
ax.set_ylim(0, 1.1)
|
148 |
-
ax.set_ylabel('Probability'
|
149 |
-
ax.set_title('Sentiment Prediction Probabilities'
|
150 |
ax.grid(axis='y', alpha=0.3)
|
151 |
|
152 |
-
# Style improvements
|
153 |
-
ax.spines['top'].set_visible(False)
|
154 |
-
ax.spines['right'].set_visible(False)
|
155 |
-
ax.set_facecolor('#f8f9fa')
|
156 |
-
|
157 |
plt.tight_layout()
|
158 |
return fig
|
159 |
|
@@ -161,7 +142,7 @@ def create_probability_plot(probabilities: np.ndarray) -> plt.Figure:
|
|
161 |
# INTERFACE FUNCTIONS
|
162 |
# ============================================================================
|
163 |
|
164 |
-
def
|
165 |
"""Single text prediction interface"""
|
166 |
prediction, probabilities, status = make_prediction(text, model_choice)
|
167 |
|
@@ -169,63 +150,56 @@ def predict_single_text(text: str, model_choice: str) -> Tuple[str, str, str, st
|
|
169 |
confidence = max(probabilities)
|
170 |
|
171 |
# Format results
|
172 |
-
|
173 |
-
|
|
|
|
|
|
|
174 |
|
175 |
-
#
|
176 |
-
prob_details = f"""
|
177 |
-
📊 **Detailed Probabilities:**
|
178 |
-
- 😞 Negative: {probabilities[0]:.1%}
|
179 |
-
- 😊 Positive: {probabilities[1]:.1%}
|
180 |
-
"""
|
181 |
-
|
182 |
-
# Confidence interpretation
|
183 |
if confidence >= 0.8:
|
184 |
-
|
185 |
elif confidence >= 0.6:
|
186 |
-
|
187 |
else:
|
188 |
-
|
189 |
|
190 |
# Create plot
|
191 |
-
plot =
|
192 |
|
193 |
-
return
|
194 |
else:
|
195 |
-
return
|
196 |
|
197 |
-
def
|
198 |
-
"""Process
|
199 |
if file is None:
|
200 |
-
return "
|
201 |
|
202 |
if MODELS is None:
|
203 |
-
return "
|
204 |
|
205 |
try:
|
206 |
-
# Read file
|
207 |
if file.name.endswith('.txt'):
|
208 |
-
|
|
|
209 |
texts = [line.strip() for line in content.split('\n') if line.strip()]
|
210 |
elif file.name.endswith('.csv'):
|
211 |
-
df = pd.read_csv(file)
|
212 |
texts = df.iloc[:, 0].astype(str).tolist()
|
213 |
else:
|
214 |
-
return "
|
215 |
|
216 |
if not texts:
|
217 |
-
return "
|
218 |
|
219 |
-
# Limit
|
220 |
if len(texts) > max_texts:
|
221 |
texts = texts[:max_texts]
|
222 |
-
status_msg = f"⚠️ Processing limited to {max_texts} texts due to size constraints.\n"
|
223 |
-
else:
|
224 |
-
status_msg = ""
|
225 |
|
226 |
-
# Process
|
227 |
results = []
|
228 |
-
|
229 |
for i, text in enumerate(texts):
|
230 |
if text.strip():
|
231 |
prediction, probabilities, _ = make_prediction(text, model_choice)
|
@@ -241,526 +215,337 @@ def process_batch_file(file, model_choice: str, max_texts: int = 100) -> Tuple[s
|
|
241 |
})
|
242 |
|
243 |
if results:
|
244 |
-
# Create
|
245 |
-
results_df = pd.DataFrame(results)
|
246 |
-
|
247 |
-
# Generate summary
|
248 |
positive_count = sum(1 for r in results if r['Prediction'] == 'Positive')
|
249 |
negative_count = len(results) - positive_count
|
250 |
avg_confidence = np.mean([float(r['Confidence'].strip('%')) for r in results])
|
251 |
|
252 |
-
summary = f""
|
253 |
-
|
|
|
|
|
|
|
|
|
254 |
|
255 |
-
|
256 |
-
|
257 |
-
- 😊 Positive: {positive_count} ({positive_count/len(results):.1%})
|
258 |
-
- 😞 Negative: {negative_count} ({negative_count/len(results):.1%})
|
259 |
-
- Average Confidence: {avg_confidence:.1f}%
|
260 |
-
"""
|
261 |
|
262 |
-
#
|
263 |
-
|
|
|
|
|
264 |
|
265 |
-
return summary,
|
266 |
else:
|
267 |
-
return "
|
268 |
|
269 |
except Exception as e:
|
270 |
-
return f"
|
271 |
|
272 |
-
def
|
273 |
"""Compare predictions from different models"""
|
274 |
if MODELS is None:
|
275 |
-
return "
|
276 |
|
277 |
-
if not text
|
278 |
-
return "
|
279 |
|
280 |
available_models = get_available_models()
|
281 |
|
282 |
if len(available_models) < 2:
|
283 |
-
return "
|
284 |
|
285 |
-
|
|
|
286 |
|
287 |
for model_name in available_models:
|
288 |
prediction, probabilities, _ = make_prediction(text, model_name)
|
289 |
|
290 |
if prediction and probabilities is not None:
|
291 |
-
|
292 |
'Model': model_name,
|
293 |
'Prediction': prediction,
|
294 |
'Confidence': f"{max(probabilities):.1%}",
|
295 |
-
'Negative
|
296 |
-
'Positive
|
297 |
-
'Raw_Probs': probabilities
|
298 |
})
|
|
|
299 |
|
300 |
-
if
|
301 |
# Create comparison text
|
302 |
-
comparison_text = "
|
303 |
|
304 |
-
for result in
|
305 |
comparison_text += f"**{result['Model']}:**\n"
|
306 |
comparison_text += f"- Prediction: {result['Prediction']}\n"
|
307 |
comparison_text += f"- Confidence: {result['Confidence']}\n"
|
308 |
-
comparison_text += f"- Negative: {result['Negative
|
309 |
|
310 |
# Agreement analysis
|
311 |
-
predictions = [r['Prediction'] for r in
|
312 |
if len(set(predictions)) == 1:
|
313 |
-
comparison_text += f"
|
314 |
else:
|
315 |
-
comparison_text += "
|
316 |
-
for result in comparison_results:
|
317 |
-
comparison_text += f"- {result['Model']}: {result['Prediction']}\n"
|
318 |
|
319 |
-
# Create
|
320 |
-
fig, axes = plt.subplots(1, len(
|
321 |
|
322 |
-
if len(
|
323 |
axes = [axes]
|
324 |
|
325 |
-
for i, result in enumerate(
|
326 |
ax = axes[i]
|
327 |
|
328 |
classes = ['Negative', 'Positive']
|
329 |
colors = ['#ff6b6b', '#51cf66']
|
330 |
|
331 |
-
bars = ax.bar(classes,
|
332 |
|
333 |
-
# Add
|
334 |
-
for bar, prob in zip(bars,
|
335 |
height = bar.get_height()
|
336 |
ax.text(bar.get_x() + bar.get_width()/2., height + 0.02,
|
337 |
f'{prob:.0%}', ha='center', va='bottom', fontweight='bold')
|
338 |
|
339 |
ax.set_ylim(0, 1.1)
|
340 |
-
ax.set_title(f"{result['Model']}\n{result['Prediction']}"
|
341 |
ax.grid(axis='y', alpha=0.3)
|
342 |
-
|
343 |
-
# Style
|
344 |
-
ax.spines['top'].set_visible(False)
|
345 |
-
ax.spines['right'].set_visible(False)
|
346 |
|
347 |
plt.tight_layout()
|
348 |
|
349 |
return comparison_text, fig
|
350 |
else:
|
351 |
-
return "
|
352 |
|
353 |
-
def get_model_info()
|
354 |
-
"""Get model information
|
355 |
if MODELS is None:
|
356 |
return """
|
357 |
-
|
358 |
|
359 |
-
Please ensure you have
|
360 |
- sentiment_analysis_pipeline.pkl (complete pipeline), OR
|
361 |
- tfidf_vectorizer.pkl + logistic_regression_model.pkl, OR
|
362 |
- tfidf_vectorizer.pkl + multinomial_nb_model.pkl
|
363 |
"""
|
364 |
|
365 |
-
|
366 |
|
367 |
-
|
368 |
-
info_text += "🔧 **Available Models:**\n\n"
|
369 |
|
370 |
if MODELS.get('pipeline_available') or (MODELS.get('vectorizer_available') and MODELS.get('lr_available')):
|
371 |
-
|
372 |
-
|
373 |
-
-
|
374 |
-
-
|
375 |
-
- Features: TF-IDF vectors (unigrams + bigrams)
|
376 |
-
- Strengths: Fast prediction, interpretable, good baseline
|
377 |
-
|
378 |
-
"""
|
379 |
|
380 |
if MODELS.get('vectorizer_available') and MODELS.get('nb_available'):
|
381 |
-
|
382 |
-
|
383 |
-
-
|
384 |
-
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
""
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
🔤 **Feature Engineering:**
|
393 |
-
- Vectorization: TF-IDF (Term Frequency-Inverse Document Frequency)
|
394 |
-
- Max Features: 5,000 most important terms
|
395 |
-
- N-grams: Unigrams (1-word) and Bigrams (2-word phrases)
|
396 |
-
- Min Document Frequency: 2 (terms must appear in at least 2 documents)
|
397 |
-
- Stop Words: English stop words removed
|
398 |
-
|
399 |
-
"""
|
400 |
-
|
401 |
-
# File status
|
402 |
-
info_text += "📁 **Model Files Status:**\n\n"
|
403 |
-
|
404 |
-
files_to_check = [
|
405 |
-
("sentiment_analysis_pipeline.pkl", "Complete LR Pipeline", MODELS.get('pipeline_available', False)),
|
406 |
-
("tfidf_vectorizer.pkl", "TF-IDF Vectorizer", MODELS.get('vectorizer_available', False)),
|
407 |
-
("logistic_regression_model.pkl", "LR Classifier", MODELS.get('lr_available', False)),
|
408 |
-
("multinomial_nb_model.pkl", "NB Classifier", MODELS.get('nb_available', False))
|
409 |
]
|
410 |
|
411 |
-
for filename,
|
412 |
status_icon = "✅" if status else "❌"
|
413 |
-
|
414 |
-
|
415 |
-
info_text += """
|
416 |
|
417 |
-
|
418 |
-
- Dataset: Product Review Sentiment Analysis
|
419 |
-
- Classes: Positive and Negative sentiment
|
420 |
-
- Preprocessing: Text cleaning, tokenization, TF-IDF vectorization
|
421 |
-
- Training: Both models trained on same feature set for fair comparison
|
422 |
-
"""
|
423 |
-
|
424 |
-
return info_text
|
425 |
|
426 |
# ============================================================================
|
427 |
# GRADIO INTERFACE
|
428 |
# ============================================================================
|
429 |
|
430 |
-
def
|
431 |
-
"""Create
|
432 |
-
|
433 |
-
# Custom CSS for better styling
|
434 |
-
css = """
|
435 |
-
.gradio-container {
|
436 |
-
font-family: 'Arial', sans-serif;
|
437 |
-
}
|
438 |
-
.main-header {
|
439 |
-
text-align: center;
|
440 |
-
color: #1f77b4;
|
441 |
-
font-size: 2.5rem;
|
442 |
-
margin-bottom: 1rem;
|
443 |
-
}
|
444 |
-
.tab-nav {
|
445 |
-
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
|
446 |
-
}
|
447 |
-
"""
|
448 |
|
449 |
-
with gr.Blocks(
|
450 |
|
451 |
# Header
|
452 |
gr.HTML("""
|
453 |
-
<div
|
454 |
-
<h1>🤖 ML Text Classification App</h1>
|
455 |
-
<p style="font-size: 1.2rem; color: #666;">
|
456 |
-
Advanced Sentiment Analysis with Multiple ML Models
|
457 |
-
</p>
|
458 |
</div>
|
459 |
""")
|
460 |
|
461 |
-
# Main
|
462 |
with gr.Tabs():
|
463 |
|
464 |
-
#
|
465 |
-
# SINGLE PREDICTION TAB
|
466 |
-
# ============================================================================
|
467 |
with gr.Tab("🔮 Single Prediction"):
|
468 |
-
gr.Markdown("### Enter text
|
469 |
|
470 |
with gr.Row():
|
471 |
-
with gr.Column(scale=
|
472 |
model_dropdown = gr.Dropdown(
|
473 |
choices=get_available_models(),
|
474 |
value=get_available_models()[0] if get_available_models() else None,
|
475 |
-
label="Choose
|
476 |
-
info="Select the ML model for prediction"
|
477 |
)
|
478 |
|
479 |
text_input = gr.Textbox(
|
480 |
lines=5,
|
481 |
-
placeholder="
|
482 |
-
label="
|
483 |
-
info="Enter any text you want to analyze for sentiment"
|
484 |
)
|
485 |
|
486 |
-
# Example texts
|
487 |
with gr.Row():
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
|
492 |
-
predict_btn = gr.Button("🚀 Analyze Sentiment", variant="primary"
|
493 |
|
494 |
-
with gr.Column(scale=
|
495 |
-
|
496 |
-
|
497 |
-
prob_details = gr.Markdown(label="Detailed Probabilities")
|
498 |
-
interpretation = gr.Markdown(label="Interpretation")
|
499 |
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
# Example text handlers
|
504 |
-
example_btn1.click(
|
505 |
-
lambda: "This product is absolutely amazing! Best purchase I've made this year.",
|
506 |
outputs=text_input
|
507 |
)
|
508 |
-
|
509 |
-
lambda: "Terrible quality, broke
|
510 |
outputs=text_input
|
511 |
)
|
512 |
-
|
513 |
lambda: "It's okay, nothing special but does the job.",
|
514 |
outputs=text_input
|
515 |
)
|
516 |
|
517 |
# Prediction handler
|
518 |
predict_btn.click(
|
519 |
-
|
520 |
inputs=[text_input, model_dropdown],
|
521 |
-
outputs=[
|
522 |
)
|
523 |
|
524 |
-
#
|
525 |
-
# BATCH PROCESSING TAB
|
526 |
-
# ============================================================================
|
527 |
with gr.Tab("📁 Batch Processing"):
|
528 |
-
gr.Markdown("### Upload a
|
529 |
|
530 |
with gr.Row():
|
531 |
with gr.Column():
|
532 |
file_upload = gr.File(
|
533 |
-
label="
|
534 |
-
file_types=[".txt", ".csv"]
|
535 |
-
info="Upload a .txt file (one text per line) or .csv file (text in first column)"
|
536 |
)
|
537 |
|
538 |
-
|
539 |
choices=get_available_models(),
|
540 |
value=get_available_models()[0] if get_available_models() else None,
|
541 |
-
label="
|
542 |
)
|
543 |
|
544 |
-
|
545 |
minimum=10,
|
546 |
-
maximum=
|
547 |
value=100,
|
548 |
step=10,
|
549 |
-
label="
|
550 |
-
info="Limit processing for performance"
|
551 |
)
|
552 |
|
553 |
-
process_btn = gr.Button("📊 Process File", variant="primary"
|
554 |
|
555 |
with gr.Column():
|
556 |
-
|
557 |
-
|
558 |
-
download_file = gr.File(
|
559 |
-
label="Download Results",
|
560 |
-
visible=False
|
561 |
-
)
|
562 |
-
|
563 |
-
# File format examples
|
564 |
-
with gr.Accordion("📄 Example File Formats", open=False):
|
565 |
-
gr.Markdown("""
|
566 |
-
**Text File (.txt):**
|
567 |
-
```
|
568 |
-
This product is amazing!
|
569 |
-
Terrible quality, very disappointed
|
570 |
-
Great service and fast delivery
|
571 |
-
```
|
572 |
-
|
573 |
-
**CSV File (.csv):**
|
574 |
-
```
|
575 |
-
text,category
|
576 |
-
"Amazing product, love it!",review
|
577 |
-
"Poor quality, not satisfied",review
|
578 |
-
```
|
579 |
-
""")
|
580 |
-
|
581 |
-
# Batch processing handler
|
582 |
-
def handle_batch_processing(file, model_choice, max_texts):
|
583 |
-
summary, csv_data = process_batch_file(file, model_choice, max_texts)
|
584 |
-
|
585 |
-
if csv_data:
|
586 |
-
# Save CSV data to a temporary file for download
|
587 |
-
csv_file = gr.File(value=io.StringIO(csv_data), visible=True)
|
588 |
-
return summary, csv_file
|
589 |
-
else:
|
590 |
-
return summary, gr.File(visible=False)
|
591 |
|
|
|
592 |
process_btn.click(
|
593 |
-
|
594 |
-
inputs=[file_upload,
|
595 |
-
outputs=[
|
596 |
)
|
597 |
|
598 |
-
#
|
599 |
-
# MODEL COMPARISON TAB
|
600 |
-
# ============================================================================
|
601 |
with gr.Tab("⚖️ Model Comparison"):
|
602 |
-
gr.Markdown("### Compare predictions from different models
|
603 |
|
604 |
with gr.Row():
|
605 |
with gr.Column():
|
606 |
-
|
607 |
lines=4,
|
608 |
-
placeholder="Enter text to
|
609 |
-
label="
|
610 |
-
info="Try texts with mixed sentiment for interesting comparisons"
|
611 |
)
|
612 |
|
613 |
-
compare_btn = gr.Button("🔍 Compare
|
614 |
|
615 |
-
# Quick examples for comparison
|
616 |
with gr.Row():
|
617 |
comp_ex1 = gr.Button("Mixed Example 1", size="sm")
|
618 |
comp_ex2 = gr.Button("Mixed Example 2", size="sm")
|
619 |
-
comp_ex3 = gr.Button("Mixed Example 3", size="sm")
|
620 |
|
621 |
with gr.Column():
|
622 |
-
|
623 |
|
624 |
-
|
625 |
-
comparison_plot = gr.Plot(label="Model Comparison Visualization")
|
626 |
|
627 |
-
#
|
628 |
comp_ex1.click(
|
629 |
lambda: "This movie was okay but not great.",
|
630 |
-
outputs=
|
631 |
)
|
632 |
comp_ex2.click(
|
633 |
lambda: "The product is fine, I guess.",
|
634 |
-
outputs=
|
635 |
-
)
|
636 |
-
comp_ex3.click(
|
637 |
-
lambda: "Could be better, could be worse.",
|
638 |
-
outputs=comparison_text
|
639 |
)
|
640 |
|
641 |
-
#
|
642 |
compare_btn.click(
|
643 |
-
|
644 |
-
inputs=
|
645 |
-
outputs=[
|
646 |
)
|
647 |
|
648 |
-
#
|
649 |
-
# MODEL INFO TAB
|
650 |
-
# ============================================================================
|
651 |
with gr.Tab("📊 Model Info"):
|
652 |
-
|
653 |
value=get_model_info(),
|
654 |
label="Model Information"
|
655 |
)
|
656 |
|
657 |
-
|
658 |
-
|
659 |
-
get_model_info,
|
660 |
-
outputs=model_info_display
|
661 |
-
)
|
662 |
-
|
663 |
-
# ============================================================================
|
664 |
-
# HELP TAB
|
665 |
-
# ============================================================================
|
666 |
-
with gr.Tab("❓ Help"):
|
667 |
-
gr.Markdown("""
|
668 |
-
## 📚 How to Use This App
|
669 |
-
|
670 |
-
### 🔮 Single Prediction
|
671 |
-
1. **Select a model** from the dropdown (Logistic Regression or Multinomial Naive Bayes)
|
672 |
-
2. **Enter text** in the text area (product reviews, comments, feedback)
|
673 |
-
3. **Click 'Analyze Sentiment'** to get sentiment analysis results
|
674 |
-
4. **View results:** prediction, confidence score, and probability breakdown
|
675 |
-
5. **Try examples:** Use the provided example buttons to test the models
|
676 |
-
|
677 |
-
### 📁 Batch Processing
|
678 |
-
1. **Prepare your file:**
|
679 |
-
- **.txt file:** One text per line
|
680 |
-
- **.csv file:** Text in the first column
|
681 |
-
2. **Upload the file** using the file uploader
|
682 |
-
3. **Select a model** for processing
|
683 |
-
4. **Adjust max texts** slider if needed
|
684 |
-
5. **Click 'Process File'** to analyze all texts
|
685 |
-
6. **Download results** as CSV file with predictions and probabilities
|
686 |
-
|
687 |
-
### ⚖️ Model Comparison
|
688 |
-
1. **Enter text** you want to analyze
|
689 |
-
2. **Click 'Compare All Models'** to get predictions from both models
|
690 |
-
3. **View comparison results** showing predictions and confidence scores
|
691 |
-
4. **Analyze agreement:** See if models agree or disagree
|
692 |
-
5. **Compare visualizations:** Side-by-side probability charts
|
693 |
-
|
694 |
-
### 🔧 Troubleshooting
|
695 |
-
|
696 |
-
**Models not loading:**
|
697 |
-
- Ensure model files (.pkl) are in the 'models/' directory
|
698 |
-
- Check that required files exist:
|
699 |
-
- tfidf_vectorizer.pkl (required)
|
700 |
-
- sentiment_analysis_pipeline.pkl (for LR pipeline)
|
701 |
-
- logistic_regression_model.pkl (for LR individual)
|
702 |
-
- multinomial_nb_model.pkl (for NB model)
|
703 |
-
|
704 |
-
**Prediction errors:**
|
705 |
-
- Make sure input text is not empty
|
706 |
-
- Try shorter texts if getting memory errors
|
707 |
-
- Check that text contains readable characters
|
708 |
-
|
709 |
-
**File upload issues:**
|
710 |
-
- Ensure file format is .txt or .csv
|
711 |
-
- Check file encoding (should be UTF-8)
|
712 |
-
- Verify CSV has text in the first column
|
713 |
-
|
714 |
-
### 💻 Project Structure
|
715 |
-
```
|
716 |
-
gradio_ml_app/
|
717 |
-
├── app.py # Main application
|
718 |
-
├── requirements.txt # Dependencies
|
719 |
-
├── models/ # Model files
|
720 |
-
│ ├── sentiment_analysis_pipeline.pkl # LR complete pipeline
|
721 |
-
│ ├── tfidf_vectorizer.pkl # Feature extraction
|
722 |
-
│ ├── logistic_regression_model.pkl # LR classifier
|
723 |
-
│ └── multinomial_nb_model.pkl # NB classifier
|
724 |
-
└── sample_data/ # Sample files
|
725 |
-
├── sample_texts.txt
|
726 |
-
└── sample_data.csv
|
727 |
-
```
|
728 |
-
""")
|
729 |
|
730 |
# Footer
|
731 |
gr.HTML("""
|
732 |
-
<div style=
|
733 |
<p><strong>🤖 ML Text Classification App</strong></p>
|
734 |
-
<p>Built with
|
735 |
-
<p><small>
|
736 |
-
<p><small>This app demonstrates sentiment analysis using trained ML models</small></p>
|
737 |
</div>
|
738 |
""")
|
739 |
|
740 |
return app
|
741 |
|
742 |
# ============================================================================
|
743 |
-
# MAIN
|
744 |
# ============================================================================
|
745 |
|
746 |
if __name__ == "__main__":
|
747 |
-
# Check
|
748 |
if MODELS is None:
|
749 |
print("⚠️ Warning: No models loaded!")
|
750 |
-
print("Please ensure you have the required model files in the 'models/' directory.")
|
751 |
else:
|
752 |
-
|
753 |
-
print(f"✅ Successfully loaded {len(
|
754 |
-
|
755 |
-
# Create and launch the interface
|
756 |
-
app = create_interface()
|
757 |
|
758 |
-
# Launch
|
|
|
759 |
app.launch(
|
760 |
-
server_name="0.0.0.0",
|
761 |
-
server_port=7860,
|
762 |
-
share=False,
|
763 |
-
debug=True
|
764 |
-
show_error=True, # Show detailed errors
|
765 |
-
inbrowser=True # Open browser automatically
|
766 |
)
|
|
|
1 |
+
# GRADIO ML CLASSIFICATION APP - SIMPLIFIED VERSION
|
2 |
+
# =================================================
|
3 |
|
4 |
import gradio as gr
|
5 |
import pandas as pd
|
6 |
import numpy as np
|
7 |
import joblib
|
8 |
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
|
|
9 |
import warnings
|
10 |
+
import tempfile
|
11 |
+
import os
|
12 |
+
from typing import Tuple, List, Optional
|
13 |
+
|
14 |
warnings.filterwarnings('ignore')
|
15 |
|
16 |
# ============================================================================
|
17 |
+
# MODEL LOADING
|
18 |
# ============================================================================
|
19 |
|
20 |
def load_models():
|
|
|
22 |
models = {}
|
23 |
|
24 |
try:
|
25 |
+
# Load pipeline
|
26 |
try:
|
27 |
models['pipeline'] = joblib.load('models/sentiment_analysis_pipeline.pkl')
|
28 |
models['pipeline_available'] = True
|
29 |
+
except:
|
30 |
models['pipeline_available'] = False
|
31 |
|
32 |
+
# Load vectorizer
|
33 |
try:
|
34 |
models['vectorizer'] = joblib.load('models/tfidf_vectorizer.pkl')
|
35 |
models['vectorizer_available'] = True
|
36 |
+
except:
|
37 |
models['vectorizer_available'] = False
|
38 |
|
39 |
+
# Load LR model
|
40 |
try:
|
41 |
models['logistic_regression'] = joblib.load('models/logistic_regression_model.pkl')
|
42 |
models['lr_available'] = True
|
43 |
+
except:
|
44 |
models['lr_available'] = False
|
45 |
|
46 |
+
# Load NB model
|
47 |
try:
|
48 |
models['naive_bayes'] = joblib.load('models/multinomial_nb_model.pkl')
|
49 |
models['nb_available'] = True
|
50 |
+
except:
|
51 |
models['nb_available'] = False
|
52 |
|
53 |
+
# Check if we have working models
|
54 |
pipeline_ready = models['pipeline_available']
|
55 |
individual_ready = models['vectorizer_available'] and (models['lr_available'] or models['nb_available'])
|
56 |
|
57 |
+
return models if (pipeline_ready or individual_ready) else None
|
|
|
|
|
|
|
58 |
|
59 |
except Exception as e:
|
60 |
print(f"Error loading models: {e}")
|
|
|
64 |
MODELS = load_models()
|
65 |
|
66 |
# ============================================================================
|
67 |
+
# CORE FUNCTIONS
|
68 |
# ============================================================================
|
69 |
|
70 |
+
def get_available_models():
|
71 |
+
"""Get available model names"""
|
72 |
if MODELS is None:
|
73 |
+
return ["No models available"]
|
74 |
+
|
75 |
+
available = []
|
76 |
+
if MODELS.get('pipeline_available') or (MODELS.get('vectorizer_available') and MODELS.get('lr_available')):
|
77 |
+
available.append("Logistic Regression")
|
78 |
|
79 |
+
if MODELS.get('vectorizer_available') and MODELS.get('nb_available'):
|
80 |
+
available.append("Multinomial Naive Bayes")
|
81 |
+
|
82 |
+
return available if available else ["No models available"]
|
83 |
+
|
84 |
+
def make_prediction(text, model_choice):
|
85 |
+
"""Make prediction using selected model"""
|
86 |
+
if MODELS is None or not text.strip():
|
87 |
+
return None, None, "Please enter text and ensure models are loaded"
|
88 |
|
89 |
try:
|
|
|
|
|
|
|
90 |
if model_choice == "Logistic Regression":
|
91 |
if MODELS.get('pipeline_available'):
|
|
|
92 |
prediction = MODELS['pipeline'].predict([text])[0]
|
93 |
probabilities = MODELS['pipeline'].predict_proba([text])[0]
|
94 |
elif MODELS.get('vectorizer_available') and MODELS.get('lr_available'):
|
|
|
95 |
X = MODELS['vectorizer'].transform([text])
|
96 |
prediction = MODELS['logistic_regression'].predict(X)[0]
|
97 |
probabilities = MODELS['logistic_regression'].predict_proba(X)[0]
|
98 |
+
else:
|
99 |
+
return None, None, "Logistic Regression model not available"
|
100 |
|
101 |
elif model_choice == "Multinomial Naive Bayes":
|
102 |
if MODELS.get('vectorizer_available') and MODELS.get('nb_available'):
|
|
|
103 |
X = MODELS['vectorizer'].transform([text])
|
104 |
prediction = MODELS['naive_bayes'].predict(X)[0]
|
105 |
probabilities = MODELS['naive_bayes'].predict_proba(X)[0]
|
106 |
+
else:
|
107 |
+
return None, None, "Naive Bayes model not available"
|
108 |
|
109 |
+
# Convert prediction
|
110 |
+
class_names = ['Negative', 'Positive']
|
111 |
+
prediction_label = class_names[prediction] if isinstance(prediction, int) else str(prediction)
|
112 |
+
|
113 |
+
return prediction_label, probabilities, "Success"
|
|
|
|
|
|
|
114 |
|
115 |
except Exception as e:
|
116 |
+
return None, None, f"Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
|
118 |
+
def create_plot(probabilities):
|
119 |
+
"""Create probability plot"""
|
120 |
fig, ax = plt.subplots(figsize=(8, 5))
|
121 |
|
122 |
+
classes = ['Negative', 'Positive']
|
123 |
colors = ['#ff6b6b', '#51cf66']
|
124 |
|
125 |
+
bars = ax.bar(classes, probabilities, color=colors, alpha=0.8)
|
126 |
|
127 |
+
# Add labels
|
128 |
for bar, prob in zip(bars, probabilities):
|
129 |
height = bar.get_height()
|
130 |
ax.text(bar.get_x() + bar.get_width()/2., height + 0.01,
|
131 |
+
f'{prob:.1%}', ha='center', va='bottom', fontweight='bold')
|
132 |
|
133 |
ax.set_ylim(0, 1.1)
|
134 |
+
ax.set_ylabel('Probability')
|
135 |
+
ax.set_title('Sentiment Prediction Probabilities')
|
136 |
ax.grid(axis='y', alpha=0.3)
|
137 |
|
|
|
|
|
|
|
|
|
|
|
138 |
plt.tight_layout()
|
139 |
return fig
|
140 |
|
|
|
142 |
# INTERFACE FUNCTIONS
|
143 |
# ============================================================================
|
144 |
|
145 |
+
def predict_text(text, model_choice):
|
146 |
"""Single text prediction interface"""
|
147 |
prediction, probabilities, status = make_prediction(text, model_choice)
|
148 |
|
|
|
150 |
confidence = max(probabilities)
|
151 |
|
152 |
# Format results
|
153 |
+
result = f"**Prediction:** {prediction} Sentiment\n"
|
154 |
+
result += f"**Confidence:** {confidence:.1%}\n\n"
|
155 |
+
result += f"**Detailed Probabilities:**\n"
|
156 |
+
result += f"- Negative: {probabilities[0]:.1%}\n"
|
157 |
+
result += f"- Positive: {probabilities[1]:.1%}\n\n"
|
158 |
|
159 |
+
# Interpretation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
if confidence >= 0.8:
|
161 |
+
result += "**High Confidence:** The model is very confident about this prediction."
|
162 |
elif confidence >= 0.6:
|
163 |
+
result += "**Medium Confidence:** The model is reasonably confident."
|
164 |
else:
|
165 |
+
result += "**Low Confidence:** The model is uncertain about this prediction."
|
166 |
|
167 |
# Create plot
|
168 |
+
plot = create_plot(probabilities)
|
169 |
|
170 |
+
return result, plot
|
171 |
else:
|
172 |
+
return f"Error: {status}", None
|
173 |
|
174 |
+
def process_file(file, model_choice, max_texts):
|
175 |
+
"""Process uploaded file"""
|
176 |
if file is None:
|
177 |
+
return "Please upload a file!", None
|
178 |
|
179 |
if MODELS is None:
|
180 |
+
return "No models loaded!", None
|
181 |
|
182 |
try:
|
183 |
+
# Read file
|
184 |
if file.name.endswith('.txt'):
|
185 |
+
with open(file.name, 'r', encoding='utf-8') as f:
|
186 |
+
content = f.read()
|
187 |
texts = [line.strip() for line in content.split('\n') if line.strip()]
|
188 |
elif file.name.endswith('.csv'):
|
189 |
+
df = pd.read_csv(file.name)
|
190 |
texts = df.iloc[:, 0].astype(str).tolist()
|
191 |
else:
|
192 |
+
return "Unsupported file format! Use .txt or .csv", None
|
193 |
|
194 |
if not texts:
|
195 |
+
return "No text found in file!", None
|
196 |
|
197 |
+
# Limit texts
|
198 |
if len(texts) > max_texts:
|
199 |
texts = texts[:max_texts]
|
|
|
|
|
|
|
200 |
|
201 |
+
# Process texts
|
202 |
results = []
|
|
|
203 |
for i, text in enumerate(texts):
|
204 |
if text.strip():
|
205 |
prediction, probabilities, _ = make_prediction(text, model_choice)
|
|
|
215 |
})
|
216 |
|
217 |
if results:
|
218 |
+
# Create summary
|
|
|
|
|
|
|
219 |
positive_count = sum(1 for r in results if r['Prediction'] == 'Positive')
|
220 |
negative_count = len(results) - positive_count
|
221 |
avg_confidence = np.mean([float(r['Confidence'].strip('%')) for r in results])
|
222 |
|
223 |
+
summary = f"**Processing Complete!**\n\n"
|
224 |
+
summary += f"**Summary Statistics:**\n"
|
225 |
+
summary += f"- Total Processed: {len(results)}\n"
|
226 |
+
summary += f"- Positive: {positive_count} ({positive_count/len(results):.1%})\n"
|
227 |
+
summary += f"- Negative: {negative_count} ({negative_count/len(results):.1%})\n"
|
228 |
+
summary += f"- Average Confidence: {avg_confidence:.1f}%\n"
|
229 |
|
230 |
+
# Create CSV for download
|
231 |
+
results_df = pd.DataFrame(results)
|
|
|
|
|
|
|
|
|
232 |
|
233 |
+
# Save to temporary file
|
234 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
|
235 |
+
results_df.to_csv(f, index=False)
|
236 |
+
temp_file = f.name
|
237 |
|
238 |
+
return summary, temp_file
|
239 |
else:
|
240 |
+
return "No valid texts could be processed!", None
|
241 |
|
242 |
except Exception as e:
|
243 |
+
return f"Error processing file: {str(e)}", None
|
244 |
|
245 |
+
def compare_models_func(text):
|
246 |
"""Compare predictions from different models"""
|
247 |
if MODELS is None:
|
248 |
+
return "No models loaded!", None
|
249 |
|
250 |
+
if not text.strip():
|
251 |
+
return "Please enter text to compare!", None
|
252 |
|
253 |
available_models = get_available_models()
|
254 |
|
255 |
if len(available_models) < 2:
|
256 |
+
return "Need at least 2 models for comparison.", None
|
257 |
|
258 |
+
results = []
|
259 |
+
all_probs = []
|
260 |
|
261 |
for model_name in available_models:
|
262 |
prediction, probabilities, _ = make_prediction(text, model_name)
|
263 |
|
264 |
if prediction and probabilities is not None:
|
265 |
+
results.append({
|
266 |
'Model': model_name,
|
267 |
'Prediction': prediction,
|
268 |
'Confidence': f"{max(probabilities):.1%}",
|
269 |
+
'Negative': f"{probabilities[0]:.1%}",
|
270 |
+
'Positive': f"{probabilities[1]:.1%}"
|
|
|
271 |
})
|
272 |
+
all_probs.append(probabilities)
|
273 |
|
274 |
+
if results:
|
275 |
# Create comparison text
|
276 |
+
comparison_text = "**Model Comparison Results:**\n\n"
|
277 |
|
278 |
+
for result in results:
|
279 |
comparison_text += f"**{result['Model']}:**\n"
|
280 |
comparison_text += f"- Prediction: {result['Prediction']}\n"
|
281 |
comparison_text += f"- Confidence: {result['Confidence']}\n"
|
282 |
+
comparison_text += f"- Negative: {result['Negative']}, Positive: {result['Positive']}\n\n"
|
283 |
|
284 |
# Agreement analysis
|
285 |
+
predictions = [r['Prediction'] for r in results]
|
286 |
if len(set(predictions)) == 1:
|
287 |
+
comparison_text += f"**Agreement:** All models agree on {predictions[0]} sentiment!"
|
288 |
else:
|
289 |
+
comparison_text += "**Disagreement:** Models have different predictions."
|
|
|
|
|
290 |
|
291 |
+
# Create comparison plot
|
292 |
+
fig, axes = plt.subplots(1, len(results), figsize=(6*len(results), 5))
|
293 |
|
294 |
+
if len(results) == 1:
|
295 |
axes = [axes]
|
296 |
|
297 |
+
for i, (result, probs) in enumerate(zip(results, all_probs)):
|
298 |
ax = axes[i]
|
299 |
|
300 |
classes = ['Negative', 'Positive']
|
301 |
colors = ['#ff6b6b', '#51cf66']
|
302 |
|
303 |
+
bars = ax.bar(classes, probs, color=colors, alpha=0.8)
|
304 |
|
305 |
+
# Add labels
|
306 |
+
for bar, prob in zip(bars, probs):
|
307 |
height = bar.get_height()
|
308 |
ax.text(bar.get_x() + bar.get_width()/2., height + 0.02,
|
309 |
f'{prob:.0%}', ha='center', va='bottom', fontweight='bold')
|
310 |
|
311 |
ax.set_ylim(0, 1.1)
|
312 |
+
ax.set_title(f"{result['Model']}\n{result['Prediction']}")
|
313 |
ax.grid(axis='y', alpha=0.3)
|
|
|
|
|
|
|
|
|
314 |
|
315 |
plt.tight_layout()
|
316 |
|
317 |
return comparison_text, fig
|
318 |
else:
|
319 |
+
return "Failed to get predictions!", None
|
320 |
|
321 |
+
def get_model_info():
|
322 |
+
"""Get model information"""
|
323 |
if MODELS is None:
|
324 |
return """
|
325 |
+
**No models loaded!**
|
326 |
|
327 |
+
Please ensure you have model files in the 'models/' directory:
|
328 |
- sentiment_analysis_pipeline.pkl (complete pipeline), OR
|
329 |
- tfidf_vectorizer.pkl + logistic_regression_model.pkl, OR
|
330 |
- tfidf_vectorizer.pkl + multinomial_nb_model.pkl
|
331 |
"""
|
332 |
|
333 |
+
info = "**Models loaded successfully!**\n\n"
|
334 |
|
335 |
+
info += "**Available Models:**\n\n"
|
|
|
336 |
|
337 |
if MODELS.get('pipeline_available') or (MODELS.get('vectorizer_available') and MODELS.get('lr_available')):
|
338 |
+
info += "**Logistic Regression**\n"
|
339 |
+
info += "- Type: Linear Classification\n"
|
340 |
+
info += "- Features: TF-IDF vectors\n"
|
341 |
+
info += "- Strengths: Fast, interpretable\n\n"
|
|
|
|
|
|
|
|
|
342 |
|
343 |
if MODELS.get('vectorizer_available') and MODELS.get('nb_available'):
|
344 |
+
info += "**Multinomial Naive Bayes**\n"
|
345 |
+
info += "- Type: Probabilistic Classification\n"
|
346 |
+
info += "- Features: TF-IDF vectors\n"
|
347 |
+
info += "- Strengths: Works well with small data\n\n"
|
348 |
+
|
349 |
+
info += "**File Status:**\n"
|
350 |
+
files = [
|
351 |
+
("sentiment_analysis_pipeline.pkl", MODELS.get('pipeline_available', False)),
|
352 |
+
("tfidf_vectorizer.pkl", MODELS.get('vectorizer_available', False)),
|
353 |
+
("logistic_regression_model.pkl", MODELS.get('lr_available', False)),
|
354 |
+
("multinomial_nb_model.pkl", MODELS.get('nb_available', False))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
355 |
]
|
356 |
|
357 |
+
for filename, status in files:
|
358 |
status_icon = "✅" if status else "❌"
|
359 |
+
info += f"- {filename}: {status_icon}\n"
|
|
|
|
|
360 |
|
361 |
+
return info
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
362 |
|
363 |
# ============================================================================
|
364 |
# GRADIO INTERFACE
|
365 |
# ============================================================================
|
366 |
|
367 |
+
def create_app():
|
368 |
+
"""Create Gradio interface"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
369 |
|
370 |
+
with gr.Blocks(title="ML Text Classification") as app:
|
371 |
|
372 |
# Header
|
373 |
gr.HTML("""
|
374 |
+
<div style="text-align: center; margin-bottom: 2rem;">
|
375 |
+
<h1 style="color: #1f77b4; font-size: 2.5rem;">🤖 ML Text Classification App</h1>
|
376 |
+
<p style="font-size: 1.2rem; color: #666;">Advanced Sentiment Analysis with Multiple ML Models</p>
|
|
|
|
|
377 |
</div>
|
378 |
""")
|
379 |
|
380 |
+
# Main interface with tabs
|
381 |
with gr.Tabs():
|
382 |
|
383 |
+
# Single Prediction Tab
|
|
|
|
|
384 |
with gr.Tab("🔮 Single Prediction"):
|
385 |
+
gr.Markdown("### Enter text and select a model for sentiment analysis")
|
386 |
|
387 |
with gr.Row():
|
388 |
+
with gr.Column(scale=1):
|
389 |
model_dropdown = gr.Dropdown(
|
390 |
choices=get_available_models(),
|
391 |
value=get_available_models()[0] if get_available_models() else None,
|
392 |
+
label="Choose Model"
|
|
|
393 |
)
|
394 |
|
395 |
text_input = gr.Textbox(
|
396 |
lines=5,
|
397 |
+
placeholder="Enter your text here...",
|
398 |
+
label="Text Input"
|
|
|
399 |
)
|
400 |
|
|
|
401 |
with gr.Row():
|
402 |
+
example1_btn = gr.Button("Good Example", size="sm")
|
403 |
+
example2_btn = gr.Button("Bad Example", size="sm")
|
404 |
+
example3_btn = gr.Button("Neutral Example", size="sm")
|
405 |
|
406 |
+
predict_btn = gr.Button("🚀 Analyze Sentiment", variant="primary")
|
407 |
|
408 |
+
with gr.Column(scale=1):
|
409 |
+
prediction_output = gr.Markdown(label="Results")
|
410 |
+
prediction_plot = gr.Plot(label="Probability Chart")
|
|
|
|
|
411 |
|
412 |
+
# Example handlers
|
413 |
+
example1_btn.click(
|
414 |
+
lambda: "This product is absolutely amazing! Best purchase ever!",
|
|
|
|
|
|
|
415 |
outputs=text_input
|
416 |
)
|
417 |
+
example2_btn.click(
|
418 |
+
lambda: "Terrible quality, broke immediately. Waste of money!",
|
419 |
outputs=text_input
|
420 |
)
|
421 |
+
example3_btn.click(
|
422 |
lambda: "It's okay, nothing special but does the job.",
|
423 |
outputs=text_input
|
424 |
)
|
425 |
|
426 |
# Prediction handler
|
427 |
predict_btn.click(
|
428 |
+
predict_text,
|
429 |
inputs=[text_input, model_dropdown],
|
430 |
+
outputs=[prediction_output, prediction_plot]
|
431 |
)
|
432 |
|
433 |
+
# Batch Processing Tab
|
|
|
|
|
434 |
with gr.Tab("📁 Batch Processing"):
|
435 |
+
gr.Markdown("### Upload a file to process multiple texts")
|
436 |
|
437 |
with gr.Row():
|
438 |
with gr.Column():
|
439 |
file_upload = gr.File(
|
440 |
+
label="Upload File (.txt or .csv)",
|
441 |
+
file_types=[".txt", ".csv"]
|
|
|
442 |
)
|
443 |
|
444 |
+
batch_model = gr.Dropdown(
|
445 |
choices=get_available_models(),
|
446 |
value=get_available_models()[0] if get_available_models() else None,
|
447 |
+
label="Model for Batch Processing"
|
448 |
)
|
449 |
|
450 |
+
max_texts = gr.Slider(
|
451 |
minimum=10,
|
452 |
+
maximum=500,
|
453 |
value=100,
|
454 |
step=10,
|
455 |
+
label="Max Texts to Process"
|
|
|
456 |
)
|
457 |
|
458 |
+
process_btn = gr.Button("📊 Process File", variant="primary")
|
459 |
|
460 |
with gr.Column():
|
461 |
+
batch_output = gr.Markdown(label="Processing Results")
|
462 |
+
download_file = gr.File(label="Download Results")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
463 |
|
464 |
+
# Process handler
|
465 |
process_btn.click(
|
466 |
+
process_file,
|
467 |
+
inputs=[file_upload, batch_model, max_texts],
|
468 |
+
outputs=[batch_output, download_file]
|
469 |
)
|
470 |
|
471 |
+
# Model Comparison Tab
|
|
|
|
|
472 |
with gr.Tab("⚖️ Model Comparison"):
|
473 |
+
gr.Markdown("### Compare predictions from different models")
|
474 |
|
475 |
with gr.Row():
|
476 |
with gr.Column():
|
477 |
+
comparison_input = gr.Textbox(
|
478 |
lines=4,
|
479 |
+
placeholder="Enter text to compare models...",
|
480 |
+
label="Text for Comparison"
|
|
|
481 |
)
|
482 |
|
483 |
+
compare_btn = gr.Button("🔍 Compare Models", variant="primary")
|
484 |
|
|
|
485 |
with gr.Row():
|
486 |
comp_ex1 = gr.Button("Mixed Example 1", size="sm")
|
487 |
comp_ex2 = gr.Button("Mixed Example 2", size="sm")
|
|
|
488 |
|
489 |
with gr.Column():
|
490 |
+
comparison_output = gr.Markdown(label="Comparison Results")
|
491 |
|
492 |
+
comparison_plot = gr.Plot(label="Model Comparison")
|
|
|
493 |
|
494 |
+
# Example handlers
|
495 |
comp_ex1.click(
|
496 |
lambda: "This movie was okay but not great.",
|
497 |
+
outputs=comparison_input
|
498 |
)
|
499 |
comp_ex2.click(
|
500 |
lambda: "The product is fine, I guess.",
|
501 |
+
outputs=comparison_input
|
|
|
|
|
|
|
|
|
502 |
)
|
503 |
|
504 |
+
# Compare handler
|
505 |
compare_btn.click(
|
506 |
+
compare_models_func,
|
507 |
+
inputs=comparison_input,
|
508 |
+
outputs=[comparison_output, comparison_plot]
|
509 |
)
|
510 |
|
511 |
+
# Model Info Tab
|
|
|
|
|
512 |
with gr.Tab("📊 Model Info"):
|
513 |
+
model_info = gr.Markdown(
|
514 |
value=get_model_info(),
|
515 |
label="Model Information"
|
516 |
)
|
517 |
|
518 |
+
refresh_btn = gr.Button("🔄 Refresh", size="sm")
|
519 |
+
refresh_btn.click(get_model_info, outputs=model_info)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
520 |
|
521 |
# Footer
|
522 |
gr.HTML("""
|
523 |
+
<div style="text-align: center; margin-top: 2rem; padding: 1rem; border-top: 1px solid #eee; color: #666;">
|
524 |
<p><strong>🤖 ML Text Classification App</strong></p>
|
525 |
+
<p>Built with Gradio | By Maaz Amjad</p>
|
526 |
+
<p><small>Part of Introduction to Large Language Models course</small></p>
|
|
|
527 |
</div>
|
528 |
""")
|
529 |
|
530 |
return app
|
531 |
|
532 |
# ============================================================================
|
533 |
+
# MAIN
|
534 |
# ============================================================================
|
535 |
|
536 |
if __name__ == "__main__":
|
537 |
+
# Check models
|
538 |
if MODELS is None:
|
539 |
print("⚠️ Warning: No models loaded!")
|
|
|
540 |
else:
|
541 |
+
available = get_available_models()
|
542 |
+
print(f"✅ Successfully loaded {len(available)} model(s): {', '.join(available)}")
|
|
|
|
|
|
|
543 |
|
544 |
+
# Launch app
|
545 |
+
app = create_app()
|
546 |
app.launch(
|
547 |
+
server_name="0.0.0.0",
|
548 |
+
server_port=7860,
|
549 |
+
share=False,
|
550 |
+
debug=True
|
|
|
|
|
551 |
)
|