Update app.py
Browse files
app.py
CHANGED
|
@@ -1,36 +1,23 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
| 3 |
import tensorflow as tf
|
| 4 |
from tensorflow import keras
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
# Load the model
|
| 9 |
-
model = keras.models.load_model('model_4.keras')
|
| 10 |
|
| 11 |
-
# Load
|
|
|
|
| 12 |
try:
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
# Get max sequence length from model input shape
|
| 21 |
-
max_length = model.input_shape[1] if len(model.input_shape) > 1 else 100
|
| 22 |
-
|
| 23 |
-
def preprocess_text(text):
|
| 24 |
-
"""Clean and preprocess the tweet text"""
|
| 25 |
-
# Convert to lowercase
|
| 26 |
-
text = text.lower()
|
| 27 |
-
# Remove URLs
|
| 28 |
-
text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE)
|
| 29 |
-
# Remove user mentions and hashtags
|
| 30 |
-
text = re.sub(r'\@\w+|\#','', text)
|
| 31 |
-
# Remove extra spaces
|
| 32 |
-
text = re.sub(r'\s+', ' ', text).strip()
|
| 33 |
-
return text
|
| 34 |
|
| 35 |
def predict_disaster(text):
|
| 36 |
"""Predict if a tweet is about a disaster or not"""
|
|
@@ -40,37 +27,31 @@ def predict_disaster(text):
|
|
| 40 |
"Not Disaster": 0.0
|
| 41 |
}, "β οΈ Please enter a tweet to classify"
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
# Determine result message
|
| 63 |
-
if disaster_prob > 0.5:
|
| 64 |
-
result = f"π¨ **DISASTER** (Confidence: {disaster_prob*100:.1f}%)"
|
| 65 |
-
emoji = "π¨"
|
| 66 |
-
else:
|
| 67 |
-
result = f"β
**NOT DISASTER** (Confidence: {not_disaster_prob*100:.1f}%)"
|
| 68 |
-
emoji = "β
"
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
| 74 |
|
| 75 |
# Example tweets for testing
|
| 76 |
examples = [
|
|
@@ -82,8 +63,13 @@ examples = [
|
|
| 82 |
["The sunset today is absolutely beautiful"],
|
| 83 |
["Residents asked to shelter in place are being notified by officers. No other evacuation or shelter in place orders are expected"],
|
| 84 |
["This is so awesome! Best day ever!"],
|
| 85 |
-
["
|
| 86 |
-
["I'm making dinner tonight, trying a new recipe"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
]
|
| 88 |
|
| 89 |
# Create Gradio interface
|
|
@@ -91,26 +77,29 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Disaster Tweet Classifier") as dem
|
|
| 91 |
gr.Markdown(
|
| 92 |
"""
|
| 93 |
# π¨ Disaster Tweet Classification
|
| 94 |
-
###
|
| 95 |
|
| 96 |
-
This
|
| 97 |
-
|
|
|
|
|
|
|
| 98 |
"""
|
| 99 |
)
|
| 100 |
|
| 101 |
with gr.Row():
|
| 102 |
with gr.Column(scale=2):
|
| 103 |
input_text = gr.Textbox(
|
| 104 |
-
label="Enter Tweet Text",
|
| 105 |
-
placeholder="Type or paste a tweet here...",
|
| 106 |
-
lines=
|
| 107 |
)
|
| 108 |
|
| 109 |
predict_btn = gr.Button("π Classify Tweet", variant="primary", size="lg")
|
|
|
|
| 110 |
|
| 111 |
with gr.Column(scale=1):
|
| 112 |
output_label = gr.Label(
|
| 113 |
-
label="Prediction Confidence",
|
| 114 |
num_top_classes=2
|
| 115 |
)
|
| 116 |
|
|
@@ -118,12 +107,15 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Disaster Tweet Classifier") as dem
|
|
| 118 |
|
| 119 |
# Examples section
|
| 120 |
gr.Markdown("### π Try These Examples:")
|
|
|
|
|
|
|
| 121 |
gr.Examples(
|
| 122 |
examples=examples,
|
| 123 |
inputs=input_text,
|
| 124 |
outputs=[output_label, output_text],
|
| 125 |
fn=predict_disaster,
|
| 126 |
-
cache_examples=False
|
|
|
|
| 127 |
)
|
| 128 |
|
| 129 |
# Event handlers
|
|
@@ -139,12 +131,40 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Disaster Tweet Classifier") as dem
|
|
| 139 |
outputs=[output_label, output_text]
|
| 140 |
)
|
| 141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
gr.Markdown(
|
| 143 |
"""
|
| 144 |
---
|
| 145 |
-
### βΉοΈ About
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
"""
|
| 149 |
)
|
| 150 |
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import numpy as np
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
print("Loading TensorFlow and Keras Hub...")
|
| 6 |
import tensorflow as tf
|
| 7 |
from tensorflow import keras
|
| 8 |
+
import keras_hub
|
| 9 |
+
print(f"TensorFlow version: {tf.__version__}")
|
| 10 |
+
print(f"Keras Hub version: {keras_hub.__version__}")
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
# Load the BERT model
|
| 13 |
+
print("Loading BERT model...")
|
| 14 |
try:
|
| 15 |
+
model = keras.models.load_model('model_4.keras')
|
| 16 |
+
print("Model loaded successfully!")
|
| 17 |
+
print(f"Model type: {type(model)}")
|
| 18 |
+
except Exception as e:
|
| 19 |
+
print(f"Error loading model: {e}")
|
| 20 |
+
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def predict_disaster(text):
|
| 23 |
"""Predict if a tweet is about a disaster or not"""
|
|
|
|
| 27 |
"Not Disaster": 0.0
|
| 28 |
}, "β οΈ Please enter a tweet to classify"
|
| 29 |
|
| 30 |
+
try:
|
| 31 |
+
# BERT model directly accepts raw text (has built-in preprocessing)
|
| 32 |
+
# Make prediction
|
| 33 |
+
prediction = model.predict([text], verbose=0)[0][0]
|
| 34 |
+
|
| 35 |
+
# Since the model uses sigmoid activation, prediction is already a probability
|
| 36 |
+
disaster_prob = float(prediction)
|
| 37 |
+
not_disaster_prob = 1 - disaster_prob
|
| 38 |
+
|
| 39 |
+
# Determine result message
|
| 40 |
+
if disaster_prob > 0.5:
|
| 41 |
+
result = f"π¨ **DISASTER** (Confidence: {disaster_prob*100:.1f}%)"
|
| 42 |
+
else:
|
| 43 |
+
result = f"β
**NOT DISASTER** (Confidence: {not_disaster_prob*100:.1f}%)"
|
| 44 |
+
|
| 45 |
+
return {
|
| 46 |
+
"Disaster": disaster_prob,
|
| 47 |
+
"Not Disaster": not_disaster_prob
|
| 48 |
+
}, result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
except Exception as e:
|
| 51 |
+
return {
|
| 52 |
+
"Disaster": 0.0,
|
| 53 |
+
"Not Disaster": 0.0
|
| 54 |
+
}, f"β Error during prediction: {str(e)}"
|
| 55 |
|
| 56 |
# Example tweets for testing
|
| 57 |
examples = [
|
|
|
|
| 63 |
["The sunset today is absolutely beautiful"],
|
| 64 |
["Residents asked to shelter in place are being notified by officers. No other evacuation or shelter in place orders are expected"],
|
| 65 |
["This is so awesome! Best day ever!"],
|
| 66 |
+
["Heard loud noises from downtown, seems like an explosion"],
|
| 67 |
+
["I'm making dinner tonight, trying a new recipe"],
|
| 68 |
+
["Buildings are collapsing after the earthquake"],
|
| 69 |
+
["Had a great time at the party last night!"],
|
| 70 |
+
["Emergency services responding to massive flooding in the area"],
|
| 71 |
+
["Can't wait for the weekend to start"],
|
| 72 |
+
["Tornado warning issued for our county, take shelter immediately"]
|
| 73 |
]
|
| 74 |
|
| 75 |
# Create Gradio interface
|
|
|
|
| 77 |
gr.Markdown(
|
| 78 |
"""
|
| 79 |
# π¨ Disaster Tweet Classification
|
| 80 |
+
### AI-Powered BERT Model to Identify Real Disaster Reports
|
| 81 |
|
| 82 |
+
This application uses a fine-tuned **BERT** (Bidirectional Encoder Representations from Transformers) model
|
| 83 |
+
to analyze tweets and classify them as either referring to a **real disaster** or **not a disaster**.
|
| 84 |
+
|
| 85 |
+
Perfect for emergency response teams, news organizations, and disaster management agencies! ππ₯π
|
| 86 |
"""
|
| 87 |
)
|
| 88 |
|
| 89 |
with gr.Row():
|
| 90 |
with gr.Column(scale=2):
|
| 91 |
input_text = gr.Textbox(
|
| 92 |
+
label="π Enter Tweet Text",
|
| 93 |
+
placeholder="Type or paste a tweet here... (e.g., 'Earthquake hits California')",
|
| 94 |
+
lines=4
|
| 95 |
)
|
| 96 |
|
| 97 |
predict_btn = gr.Button("π Classify Tweet", variant="primary", size="lg")
|
| 98 |
+
clear_btn = gr.Button("ποΈ Clear", size="sm")
|
| 99 |
|
| 100 |
with gr.Column(scale=1):
|
| 101 |
output_label = gr.Label(
|
| 102 |
+
label="π Prediction Confidence",
|
| 103 |
num_top_classes=2
|
| 104 |
)
|
| 105 |
|
|
|
|
| 107 |
|
| 108 |
# Examples section
|
| 109 |
gr.Markdown("### π Try These Examples:")
|
| 110 |
+
gr.Markdown("Click on any example below to automatically classify it")
|
| 111 |
+
|
| 112 |
gr.Examples(
|
| 113 |
examples=examples,
|
| 114 |
inputs=input_text,
|
| 115 |
outputs=[output_label, output_text],
|
| 116 |
fn=predict_disaster,
|
| 117 |
+
cache_examples=False,
|
| 118 |
+
label="Sample Tweets"
|
| 119 |
)
|
| 120 |
|
| 121 |
# Event handlers
|
|
|
|
| 131 |
outputs=[output_label, output_text]
|
| 132 |
)
|
| 133 |
|
| 134 |
+
clear_btn.click(
|
| 135 |
+
fn=lambda: ("", {"Disaster": 0.0, "Not Disaster": 0.0}, ""),
|
| 136 |
+
outputs=[input_text, output_label, output_text]
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
gr.Markdown(
|
| 140 |
"""
|
| 141 |
---
|
| 142 |
+
### βΉοΈ About This Model
|
| 143 |
+
|
| 144 |
+
**Model Architecture**: BERT Tiny (English, Uncased)
|
| 145 |
+
- **Parameters**: ~4.4M parameters
|
| 146 |
+
- **Training**: Fine-tuned on disaster tweet dataset
|
| 147 |
+
- **Accuracy**: Optimized for real-time disaster detection
|
| 148 |
+
|
| 149 |
+
**Use Cases**:
|
| 150 |
+
- π¨ Emergency response monitoring
|
| 151 |
+
- π° News verification
|
| 152 |
+
- π Social media analysis
|
| 153 |
+
- π Crisis management
|
| 154 |
+
|
| 155 |
+
**How it Works**:
|
| 156 |
+
The model uses contextual understanding to distinguish between:
|
| 157 |
+
- Real disaster reports (earthquakes, fires, accidents, floods, etc.)
|
| 158 |
+
- Casual language or metaphorical usage of disaster-related words
|
| 159 |
+
|
| 160 |
+
**Limitations**:
|
| 161 |
+
- Optimized for English tweets only
|
| 162 |
+
- May require context for ambiguous cases
|
| 163 |
+
- Should be used as a support tool, not sole decision-maker
|
| 164 |
+
|
| 165 |
+
---
|
| 166 |
+
|
| 167 |
+
**Created by**: berkeruveyik | **Model**: BERT Tiny | **Framework**: TensorFlow + Keras Hub
|
| 168 |
"""
|
| 169 |
)
|
| 170 |
|