File size: 6,043 Bytes
80e0f4f
 
87df756
 
5f5236e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80e0f4f
5f5236e
 
 
 
80e0f4f
 
 
 
 
 
 
 
 
87df756
 
 
 
5f5236e
87df756
 
 
5f5236e
87df756
 
 
 
 
 
 
 
 
80e0f4f
87df756
 
 
 
 
80e0f4f
 
 
 
 
 
 
 
 
 
 
87df756
 
 
 
 
 
 
80e0f4f
 
 
 
5f5236e
 
 
 
 
 
 
 
 
80e0f4f
 
 
 
87df756
 
 
80e0f4f
 
5f5236e
 
 
80e0f4f
 
 
87df756
80e0f4f
 
 
 
 
 
5f5236e
 
 
 
 
87df756
80e0f4f
 
 
 
 
87df756
 
80e0f4f
 
5f5236e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d8b94e
5f5236e
 
80e0f4f
 
 
 
 
 
 
 
 
 
 
 
 
87df756
 
 
 
80e0f4f
 
 
5f5236e
 
 
 
1
2
3
4
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import gradio as gr
import numpy as np
import os

# Lazy import - sadece model yüklerken import et
def load_model():
    """Model ve gerekli kütüphaneleri lazy loading ile yükle"""
    print("Loading TensorFlow...")
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # TensorFlow loglarını azalt
    
    import tensorflow as tf
    print(f"TensorFlow version: {tf.__version__}")
    
    print("Loading Keras Hub...")
    import keras_hub
    print(f"Keras Hub version: {keras_hub.__version__}")
    
    print("Loading BERT model...")
    try:
        model = tf.keras.models.load_model('model_4.keras')
        print("✅ Model loaded successfully!")
        return model
    except Exception as e:
        print(f"❌ Error loading model: {e}")
        raise

# Model yükleme - global değişken
print("Initializing application...")
model = load_model()
print("Application ready!")

def predict_disaster(text):
    """Predict if a tweet is about a disaster or not"""
    if not text.strip():
        return {
            "Disaster": 0.0,
            "Not Disaster": 0.0
        }, "⚠️ Please enter a tweet to classify"
    
    try:
        # BERT model directly accepts raw text (has built-in preprocessing)
        prediction = model.predict([text], verbose=0)[0][0]
        
        # Calculate probabilities
        disaster_prob = float(prediction)
        not_disaster_prob = 1 - disaster_prob
        
        # Result message
        if disaster_prob > 0.5:
            result = f"🚨 **DISASTER** (Confidence: {disaster_prob*100:.1f}%)"
        else:
            result = f"✅ **NOT DISASTER** (Confidence: {not_disaster_prob*100:.1f}%)"
        
        return {
            "Disaster": disaster_prob,
            "Not Disaster": not_disaster_prob
        }, result
    
    except Exception as e:
        return {
            "Disaster": 0.0,
            "Not Disaster": 0.0
        }, f"❌ Error during prediction: {str(e)}"

# Example tweets for testing
examples = [
    ["Our Deeds are the Reason of this #earthquake May ALLAH Forgive us all"],
    ["Forest fire near La Ronge Sask. Canada"],
    ["13,000 people receive #wildfires evacuation orders in California"],
    ["Just happened a terrible car crash"],
    ["I love summer days at the beach with friends"],
    ["The sunset today is absolutely beautiful"],
    ["Residents asked to shelter in place are being notified by officers. No other evacuation or shelter in place orders are expected"],
    ["This is so awesome! Best day ever!"],
    ["Heard loud noises from downtown, seems like an explosion"],
    ["I'm making dinner tonight, trying a new recipe"],
    ["Buildings are collapsing after the earthquake"],
    ["Had a great time at the party last night!"],
    ["Emergency services responding to massive flooding in the area"],
    ["Can't wait for the weekend to start"],
    ["Tornado warning issued for our county, take shelter immediately"]
]

# Create Gradio interface
with gr.Blocks(theme=gr.themes.Soft(), title="Disaster Tweet Classifier") as demo:
    gr.Markdown("""
    # 🚨 Disaster Tweet Classification
    ### AI-Powered BERT Model to Identify Real Disaster Reports
    
    This application uses a fine-tuned **BERT** (Bidirectional Encoder Representations from Transformers) model 
    to analyze tweets and classify them as either referring to a **real disaster** or **not a disaster**.
    
    Perfect for emergency response teams, news organizations, and disaster management agencies! 🚑🔥🌊
    """)
    
    with gr.Row():
        with gr.Column(scale=2):
            input_text = gr.Textbox(
                label="📝 Enter Tweet Text",
                placeholder="Type or paste a tweet here... (e.g., 'Earthquake hits California')",
                lines=4
            )
            
            with gr.Row():
                clear_btn = gr.Button("🗑️ Clear", variant="secondary")
                predict_btn = gr.Button("🔍 Classify Tweet", variant="primary", size="lg")
            
        with gr.Column(scale=1):
            output_label = gr.Label(
                label="📊 Prediction Confidence",
                num_top_classes=2
            )
    
    output_text = gr.Markdown(label="Result")
    
    # Examples section
    gr.Markdown("""
    ---
    ### 📝 Try These Examples:
    Click on any example below to automatically classify it
    """)
    
    gr.Examples(
        examples=examples,
        inputs=input_text,
        outputs=[output_label, output_text],
        fn=predict_disaster,
        cache_examples=False,
        label="Sample Tweets"
    )
    
    gr.Markdown("""
    ---
    ### ℹ️ About This Model
    
    **Model Architecture**: BERT Tiny (English, Uncased)
    - **Parameters**: ~4.4M parameters
    - **Training**: Fine-tuned on disaster tweet dataset
    - **Accuracy**: Optimized for real-time disaster detection
    
    **Use Cases**:
    - 🚨 Emergency response monitoring
    - 📰 News verification
    - 🌐 Social media analysis
    - 🔍 Crisis management
    
    **How it Works**:
    The model uses contextual understanding to distinguish between:
    - Real disaster reports (earthquakes, fires, accidents, floods, etc.)
    - Casual language or metaphorical usage of disaster-related words
    
    **Limitations**:
    - Optimized for English tweets only
    - May require context for ambiguous cases
    - Should be used as a support tool, not sole decision-maker
    

    """)
    
    # Event handlers
    predict_btn.click(
        fn=predict_disaster,
        inputs=input_text,
        outputs=[output_label, output_text]
    )
    
    input_text.submit(
        fn=predict_disaster,
        inputs=input_text,
        outputs=[output_label, output_text]
    )
    
    clear_btn.click(
        fn=lambda: ("", {"Disaster": 0.0, "Not Disaster": 0.0}, ""),
        outputs=[input_text, output_label, output_text]
    )

# Launch the app
if __name__ == "__main__":
    demo.launch(
        share=False,
        debug=False
    )