AbdullahImran commited on
Commit
04fa07a
·
verified ·
1 Parent(s): 8d17bd3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -102
app.py CHANGED
@@ -1,111 +1,157 @@
1
- import gradio as gr
2
- import tensorflow as tf
3
- from PIL import Image
4
  import numpy as np
5
- import tensorflow as tf
6
- import keras.backend as K
7
-
8
-
9
- # Define focal loss
10
- def focal_loss(gamma=2., alpha=0.25):
11
- def focal_loss_fixed(y_true, y_pred):
12
- y_pred = tf.clip_by_value(y_pred, K.epsilon(), 1. - K.epsilon())
13
- cross_entropy = -y_true * tf.math.log(y_pred)
14
- weight = alpha * y_true * tf.math.pow((1 - y_pred), gamma)
15
- loss = weight * cross_entropy
16
- return tf.reduce_sum(loss, axis=-1)
17
- return focal_loss_fixed
18
-
19
-
20
- # Load models
21
- vgg16_model = tf.keras.models.load_model(
22
- "vgg16_best_model.keras"
23
- )
24
-
25
- xception_model = tf.keras.models.load_model(
26
- 'xception_best.keras',
27
- custom_objects={'focal_loss_fixed': focal_loss()}
28
  )
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- def predict_fire(image):
32
- img = Image.fromarray(image).convert("RGB")
33
-
34
- # Preprocess for vgg16_model (128x128 input size)
35
- vgg16_img = img.resize((128, 128))
36
- vgg16_img_array = np.array(vgg16_img) / 255.0
37
- vgg16_img_array = np.expand_dims(vgg16_img_array, axis=0)
38
-
39
- # Fire detection using vgg16_model
40
- fire_pred = vgg16_model.predict(vgg16_img_array)
41
- fire_status = "Fire Detected" if fire_pred[0][0] > 0.5 else "No Fire Detected"
42
-
43
- # If fire is detected, preprocess for xception_model (224x224 input size)
44
- if fire_status == "Fire Detected":
45
- xception_img = img.resize((224, 224))
46
- xception_img_array = np.array(xception_img) / 255.0
47
- xception_img_array = np.expand_dims(xception_img_array, axis=0)
48
-
49
- # Severity prediction using xception_model
50
- severity_pred = xception_model.predict(xception_img_array)
51
- severity_level = np.argmax(severity_pred[0])
52
- severity = ["Mild", "Moderate", "Severe"][severity_level]
53
-
54
- # Static rule-based recommendations with detailed instructions
55
- if severity == "Mild":
56
- recommendation = (
57
- "Fire detected is mild and manageable. "
58
- "For the Fire Department: Ensure continuous monitoring of the fire. "
59
- "Deploy fire trucks and extinguishing equipment if necessary to prevent escalation. "
60
- "For the Public: Stay alert and stay indoors. Evacuate only if advised by authorities. "
61
- "Ensure clear access routes for emergency services. "
62
- "Keep fire safety equipment such as fire extinguishers readily available."
63
- )
64
- elif severity == "Moderate":
65
- recommendation = (
66
- "Fire detected is moderate and poses a significant risk. "
67
- "For the Fire Department: Immediate response is needed. "
68
- "Deploy sufficient fire trucks, helicopters (if possible), and personnel to contain the fire. "
69
- "Establish firebreaks and coordinate with neighboring departments. "
70
- "For the Public: Evacuate the area promptly as the fire might spread. "
71
- "Follow evacuation routes and do not return to the area until authorities deem it safe. "
72
- "Be cautious of smoke inhalation, and wear protective masks if available."
73
- )
74
- else: # Severe
75
- recommendation = (
76
- "Severe fire detected with rapid spread potential. Immediate action is critical. "
77
- "For the Fire Department: Prioritize evacuation operations. "
78
- "Deploy all available resources, including specialized teams and air support. "
79
- "Set up perimeters around the affected area and prevent access. "
80
- "Coordinate with national agencies for additional resources and backup. "
81
- "For the Public: Evacuate immediately. Leave all belongings behind and proceed to designated safe zones. "
82
- "Avoid smoke exposure and keep away from fire zones. Follow all official instructions and do not attempt to return to the area until clearance is given by emergency services. "
83
- "Remain in contact with local authorities for further updates."
84
- )
85
-
86
- else:
87
- severity = "N/A"
88
- recommendation = (
89
- "No fire detected. However, always be cautious of any unusual smoke or smells in your environment. "
90
- "Ensure that fire alarms are functioning, and regularly check fire extinguishers. "
91
- "Stay prepared by familiarizing yourself with fire evacuation routes and emergency contact numbers."
92
- )
93
-
94
- return fire_status, severity, recommendation
95
-
96
-
97
- # Gradio interface
98
  interface = gr.Interface(
99
- fn=predict_fire,
100
- inputs=gr.Image(type="numpy", label="Upload Image"),
101
  outputs=[
102
- gr.Textbox(label="Fire Status"),
103
- gr.Textbox(label="Severity Level"),
104
- gr.Textbox(label="Recommendation")
105
  ],
106
- title="Fire Prediction and Severity Classification",
107
- description="Upload an image to predict fire and its severity level (Mild, Moderate, Severe), and get recommendations.",
108
  )
109
 
110
- if __name__ == "__main__":
111
- interface.launch()
 
1
+ import os
2
+ import requests
3
+ import pandas as pd
4
  import numpy as np
5
+ import joblib
6
+ import google.generativeai as genai
7
+ import gradio as gr
8
+ from google.colab import drive, userdata
9
+ from datetime import datetime, timedelta
10
+ from tensorflow.keras.models import load_model
11
+ from tensorflow.keras.preprocessing import image as keras_image
12
+ from tensorflow.keras.applications.vgg16 import preprocess_input as vgg_preprocess
13
+ from tensorflow.keras.applications.xception import preprocess_input as xce_preprocess
14
+ from tensorflow.keras.losses import BinaryFocalCrossentropy
15
+
16
+ # --- CONFIGURATION ---
17
+ # Coordinates for a representative forest area in Pakistan
18
+ FOREST_COORDS = {'Pakistan Forest': (34.0, 73.0)}
19
+ API_URL = (
20
+ "https://archive-api.open-meteo.com/v1/archive"
21
+ "?latitude={lat}&longitude={lon}"
22
+ "&start_date={start}&end_date={end}"
23
+ "&daily=temperature_2m_max,temperature_2m_min,"
24
+ "precipitation_sum,windspeed_10m_max,"
25
+ "relative_humidity_2m_max,relative_humidity_2m_min"
26
+ "&timezone=UTC"
 
27
  )
28
 
29
+ # --- GEMINI SETUP ---
30
+ GOOGLE_API_KEY = userdata.get('GOOGLE_API_KEY')
31
+ genai.configure(api_key=GOOGLE_API_KEY)
32
+ flash = genai.GenerativeModel('gemini-1.5-flash')
33
+
34
+ # --- LOAD MODELS ---
35
+ def load_models():
36
+ drive.mount('/content/drive', force_remount=False)
37
+ # Fire detection (VGG16 binary classifier)
38
+ vgg_model = load_model(
39
+ '/content/drive/MyDrive/vgg16_focal_unfreeze_more.keras',
40
+ custom_objects={'BinaryFocalCrossentropy': BinaryFocalCrossentropy}
41
+ )
42
+ # Severity classification (Xception + RF/XGB ensemble)
43
+ def focal_loss_fixed(gamma=2., alpha=.25):
44
+ import tensorflow.keras.backend as K
45
+ def loss_fn(y_true, y_pred):
46
+ eps = K.epsilon(); y_pred = K.clip(y_pred, eps, 1.-eps)
47
+ ce = -y_true * K.log(y_pred)
48
+ w = alpha * K.pow(1-y_pred, gamma)
49
+ return K.mean(w*ce, axis=-1)
50
+ return loss_fn
51
+ xce_model = load_model(
52
+ '/content/drive/My Drive/severity_post_tta.keras',
53
+ custom_objects={'focal_loss_fixed': focal_loss_fixed()}
54
+ )
55
+ rf_model = joblib.load('/content/drive/My Drive/ensemble_rf_model.pkl')
56
+ xgb_model = joblib.load('/content/drive/My Drive/ensemble_xgb_model.pkl')
57
+ # Weather trend (Logistic Regression)
58
+ lr_model = joblib.load('/content/drive/MyDrive/wildfire_logistic_model_synthetic.joblib')
59
+ return vgg_model, xce_model, rf_model, xgb_model, lr_model
60
+
61
+ vgg_model, xception_model, rf_model, xgb_model, lr_model = load_models()
62
+
63
+ # --- LABEL MAPS ---
64
+ target_map = {0: 'mild', 1: 'moderate', 2: 'severe'}
65
+ trend_map = {1: 'increase', 0: 'same', -1: 'decrease'}
66
+ trend_rules = {
67
+ 'mild': {'decrease':'mild','same':'mild','increase':'moderate'},
68
+ 'moderate':{'decrease':'mild','same':'moderate','increase':'severe'},
69
+ 'severe': {'decrease':'moderate','same':'severe','increase':'severe'}
70
+ }
71
+
72
+ # --- PIPELINE FUNCTIONS ---
73
+ def detect_fire(img):
74
+ x = keras_image.img_to_array(img.resize((128,128)))[None]
75
+ x = vgg_preprocess(x)
76
+ prob = float(vgg_model.predict(x)[0][0])
77
+ return prob >= 0.5, prob
78
+
79
+
80
+ def classify_severity(img):
81
+ x = keras_image.img_to_array(img.resize((224,224)))[None]
82
+ x = xce_preprocess(x)
83
+ preds = xception_model.predict(x)
84
+ rf_p = rf_model.predict(preds)[0]
85
+ xgb_p = xgb_model.predict(preds)[0]
86
+ ensemble = int(round((rf_p + xgb_p)/2))
87
+ return target_map.get(ensemble, 'moderate')
88
+
89
+
90
+ def fetch_weather_trend(lat, lon):
91
+ end = datetime.utcnow()
92
+ start = end - timedelta(days=1)
93
+ url = API_URL.format(lat=lat, lon=lon,
94
+ start=start.strftime('%Y-%m-%d'),
95
+ end=end.strftime('%Y-%m-%d'))
96
+ data = requests.get(url).json().get('daily', {})
97
+ df = pd.DataFrame(data)
98
+ # convert to numeric
99
+ for c in ['precipitation_sum','temperature_2m_max','temperature_2m_min',
100
+ 'relative_humidity_2m_max','relative_humidity_2m_min','windspeed_10m_max']:
101
+ df[c] = pd.to_numeric(df.get(c, []), errors='coerce')
102
+ df['precipitation'] = df['precipitation_sum'].fillna(0)
103
+ df['temperature'] = (df['temperature_2m_max'] + df['temperature_2m_min'])/2
104
+ df['humidity'] = (df['relative_humidity_2m_max'] + df['relative_humidity_2m_min'])/2
105
+ df['wind_speed'] = df['windspeed_10m_max']
106
+ df['fire_risk_score'] = (
107
+ 0.4*(df['temperature']/55) +
108
+ 0.2*(1-df['humidity']/100) +
109
+ 0.3*(df['wind_speed']/60) +
110
+ 0.1*(1-df['precipitation']/50)
111
+ )
112
+ feats = df[['temperature','humidity','wind_speed','precipitation','fire_risk_score']]
113
+ v = feats.fillna(feats.mean()).iloc[-1].values.reshape(1,-1)
114
+ trend_cl = lr_model.predict(v)[0]
115
+ return trend_map.get(trend_cl)
116
+
117
+
118
+ def generate_recommendations(wildfire_present, severity, weather_trend):
119
+ prompt = f"""
120
+ You are a wildfire management expert.
121
+ - Wildfire Present: {wildfire_present}
122
+ - Severity: {severity}
123
+ - Weather Trend: {weather_trend}
124
+ Provide:
125
+ 1. Immediate actions
126
+ 2. Evacuation guidelines
127
+ 3. Short-term containment
128
+ 4. Long-term prevention & recovery
129
+ 5. Community education
130
+ """
131
+ return flash.generate_content(prompt).text
132
+
133
+ # --- GRADIO INTERFACE ---
134
+ def pipeline(image):
135
+ img = Image.fromarray(image).convert('RGB')
136
+ fire, prob = detect_fire(img)
137
+ if not fire:
138
+ return f"No wildfire detected (prob={prob:.2f})", "N/A", "No wildfire detected. Stay alert."
139
+ severity = classify_severity(img)
140
+ trend = fetch_weather_trend(*FOREST_COORDS['Pakistan Forest'])
141
+ recs = generate_recommendations(True, severity, trend)
142
+ return f"Fire Detected (prob={prob:.2f})", severity.title(), recs
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  interface = gr.Interface(
145
+ fn=pipeline,
146
+ inputs=gr.Image(type='numpy', label='Upload Wildfire Image'),
147
  outputs=[
148
+ gr.Textbox(label='Fire Status'),
149
+ gr.Textbox(label='Severity Level'),
150
+ gr.Markdown(label='Recommendations')
151
  ],
152
+ title='Wildfire Detection & Management Assistant',
153
+ description='Upload an image from a forest region in Pakistan to determine wildfire presence, severity, weather-driven trend, and get expert recommendations.'
154
  )
155
 
156
+ if __name__ == '__main__':
157
+ interface.launch()