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astapi import FastAPI
|
| 3 |
+
from fastapi.responses import JSONResponse
|
| 4 |
+
import tensorflow as tf
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import numpy as np
|
| 7 |
+
import joblib
|
| 8 |
+
from load import *
|
| 9 |
+
from helper import *
|
| 10 |
+
from matplotlib import pyplot as plt
|
| 11 |
+
|
| 12 |
+
def predict_fire(temp, temp_unit, humidity, wind, wind_unit, veg, elev, elev_unit, use_trust):
|
| 13 |
+
input_data = {
|
| 14 |
+
"temperature": convert_temperature(temp, temp_unit),
|
| 15 |
+
"humidity": humidity,
|
| 16 |
+
"wind_speed": convert_wind_speed(wind, wind_unit),
|
| 17 |
+
"vegetation_index": veg,
|
| 18 |
+
"elevation": convert_elevation(elev, elev_unit)
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
input_df = pd.DataFrame([input_data])
|
| 22 |
+
base_prob = FireNet.predict(input_df)[0][0]
|
| 23 |
+
if use_trust:
|
| 24 |
+
trust_score = FireTrustNet.predict(FireScaler.transform(input_df))[0][0]
|
| 25 |
+
final = np.clip(base_prob * trust_score, 0, 1)
|
| 26 |
+
else:
|
| 27 |
+
final = base_prob
|
| 28 |
+
if final > 0.49:
|
| 29 |
+
verdict = "🔥 FIRE LIKELY"
|
| 30 |
+
elif final > 0.43 and final < 0.50:
|
| 31 |
+
verdict = "⚠️ Fire Possible"
|
| 32 |
+
else:
|
| 33 |
+
verdict = "🌿 Fire Unlikely"
|
| 34 |
+
return f"{verdict} ({final:.2f})"
|
| 35 |
+
|
| 36 |
+
def predict_flood(rainfall_val, rainfall_unit, water_level_val, elevation_val, elev_unit,
|
| 37 |
+
slope_val, distance_val, distance_unit, use_trustnet):
|
| 38 |
+
# Unit conversion
|
| 39 |
+
rainfall = convert_rainfall(rainfall_val, rainfall_unit)
|
| 40 |
+
elevation = convert_elevation(elevation_val, elev_unit)
|
| 41 |
+
distance = convert_distance(distance_val, distance_unit)
|
| 42 |
+
|
| 43 |
+
# Construct input for FloodNet
|
| 44 |
+
base_df = pd.DataFrame([{
|
| 45 |
+
"Rainfall": rainfall,
|
| 46 |
+
"Water Level": water_level_val,
|
| 47 |
+
"Elevation": elevation,
|
| 48 |
+
"Slope": slope_val,
|
| 49 |
+
"Distance from River": distance
|
| 50 |
+
}])
|
| 51 |
+
|
| 52 |
+
base_prob = FloodNet.predict(base_df)[0][0]
|
| 53 |
+
|
| 54 |
+
if use_trustnet:
|
| 55 |
+
trust_df = pd.DataFrame([{
|
| 56 |
+
"rainfall": rainfall,
|
| 57 |
+
"water_level": water_level_val,
|
| 58 |
+
"elevation": elevation,
|
| 59 |
+
"slope": slope_val,
|
| 60 |
+
"distance_from_river": distance
|
| 61 |
+
}])
|
| 62 |
+
trust_score = FloodTrustNet.predict(FloodScaler.transform(trust_df))[0][0]
|
| 63 |
+
final = np.clip(base_prob * trust_score, 0, 1)
|
| 64 |
+
else:
|
| 65 |
+
final = base_prob
|
| 66 |
+
|
| 67 |
+
if final > 0.49:
|
| 68 |
+
verdict = "🏞️ FV-FLOOD LIKELY"
|
| 69 |
+
elif final > 0.43 and final < 0.50:
|
| 70 |
+
verdict = "⚠️ FV-Flood Possible"
|
| 71 |
+
else:
|
| 72 |
+
verdict = "🌿 FV-Flood Unlikely"
|
| 73 |
+
return f"{verdict} ({final:.2f})"
|
| 74 |
+
|
| 75 |
+
def generate_plot(axis, use_trustnet):
|
| 76 |
+
sweep_values = np.linspace({
|
| 77 |
+
"temperature": (280, 320),
|
| 78 |
+
"humidity": (0, 100),
|
| 79 |
+
"wind_speed": (0, 50),
|
| 80 |
+
"vegetation_index": (0.0, 2.0),
|
| 81 |
+
"elevation": (0, 3000)
|
| 82 |
+
}[axis][0], {
|
| 83 |
+
"temperature": (280, 320),
|
| 84 |
+
"humidity": (0, 100),
|
| 85 |
+
"wind_speed": (0, 50),
|
| 86 |
+
"vegetation_index": (0.0, 2.0),
|
| 87 |
+
"elevation": (0, 3000)
|
| 88 |
+
}[axis][1], 100)
|
| 89 |
+
|
| 90 |
+
base_input = {
|
| 91 |
+
"temperature": 300.0,
|
| 92 |
+
"humidity": 30.0,
|
| 93 |
+
"wind_speed": 10.0,
|
| 94 |
+
"vegetation_index": 1.0,
|
| 95 |
+
"elevation": 500.0
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
sweep_df = pd.DataFrame([{
|
| 99 |
+
**base_input,
|
| 100 |
+
axis: val
|
| 101 |
+
} for val in sweep_values])
|
| 102 |
+
|
| 103 |
+
raw_probs = FireNet.predict(sweep_df).flatten()
|
| 104 |
+
if use_trustnet:
|
| 105 |
+
trust_mods = FireTrustNet.predict(FireScaler.transform(sweep_df)).flatten()
|
| 106 |
+
adjusted_probs = np.clip(raw_probs * trust_mods, 0, 1)
|
| 107 |
+
else:
|
| 108 |
+
adjusted_probs = raw_probs
|
| 109 |
+
|
| 110 |
+
fig, ax = plt.subplots()
|
| 111 |
+
ax.plot(sweep_values, raw_probs, "--", color="gray", label="Base Model")
|
| 112 |
+
if use_trustnet:
|
| 113 |
+
ax.plot(sweep_values, adjusted_probs, color="orangered", label="With FireTrustNet")
|
| 114 |
+
ax.set_xlabel(axis.replace("_", " ").title())
|
| 115 |
+
ax.set_ylabel("Fire Probability")
|
| 116 |
+
ax.set_title(f"Fire Probability vs. {axis.replace('_', ' ').title()}")
|
| 117 |
+
ax.legend()
|
| 118 |
+
ax.grid(True)
|
| 119 |
+
return fig
|
| 120 |
+
|
| 121 |
+
def generate_flood_plot(axis, use_trustnet):
|
| 122 |
+
sweep_range = {
|
| 123 |
+
"rainfall": (0, 150),
|
| 124 |
+
"water_level": (0, 8000),
|
| 125 |
+
"elevation": (0, 20),
|
| 126 |
+
"slope": (0, 20),
|
| 127 |
+
"distance_from_river": (0, 2000)
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
values = np.linspace(*sweep_range[axis], 100)
|
| 131 |
+
|
| 132 |
+
base_example = {
|
| 133 |
+
"rainfall": 50.0,
|
| 134 |
+
"water_level": 3000.0,
|
| 135 |
+
"elevation": 5.0,
|
| 136 |
+
"slope": 2.0,
|
| 137 |
+
"distance_from_river": 100.0
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
# Build test cases by sweeping one input
|
| 141 |
+
inputs = pd.DataFrame([
|
| 142 |
+
{**base_example, axis: v} for v in values
|
| 143 |
+
])
|
| 144 |
+
|
| 145 |
+
# Predict with FloodNet
|
| 146 |
+
floodnet_inputs = inputs.rename(columns={
|
| 147 |
+
"rainfall": "Rainfall",
|
| 148 |
+
"water_level": "Water Level",
|
| 149 |
+
"elevation": "Elevation",
|
| 150 |
+
"slope": "Slope",
|
| 151 |
+
"distance_from_river": "Distance from River"
|
| 152 |
+
})
|
| 153 |
+
|
| 154 |
+
base_probs = FloodNet.predict(floodnet_inputs).flatten()
|
| 155 |
+
|
| 156 |
+
if use_trustnet:
|
| 157 |
+
trust_inputs = inputs.copy()
|
| 158 |
+
trust_scores = FloodTrustNet.predict(FloodScaler.transform(trust_inputs)).flatten()
|
| 159 |
+
modulated_probs = np.clip(base_probs * trust_scores, 0, 1)
|
| 160 |
+
else:
|
| 161 |
+
modulated_probs = base_probs
|
| 162 |
+
|
| 163 |
+
# Plotting
|
| 164 |
+
fig, ax = plt.subplots()
|
| 165 |
+
ax.plot(values, base_probs, "--", color="gray", label="FloodNet")
|
| 166 |
+
if use_trustnet:
|
| 167 |
+
ax.plot(values, modulated_probs, color="blue", label="With FloodTrustNet")
|
| 168 |
+
ax.set_xlabel(axis.replace("_", " ").title())
|
| 169 |
+
ax.set_ylabel("Flood Probability")
|
| 170 |
+
ax.set_title(f"Flood Probability vs. {axis.replace('_', ' ').title()}")
|
| 171 |
+
ax.grid(True)
|
| 172 |
+
ax.legend()
|
| 173 |
+
return fig
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# Launch the app
|
| 177 |
+
with gr.Blocks(theme=gr.themes.Default(), css=".tab-nav-button { font-size: 1.1rem !important; padding: 0.8em; } ") as demo:
|
| 178 |
+
gr.Markdown("# ClimateNet - A family of tabular classification models to predict natural disasters")
|
| 179 |
+
|
| 180 |
+
with gr.Tab("🔥 FireNet"):
|
| 181 |
+
with gr.Row():
|
| 182 |
+
with gr.Column():
|
| 183 |
+
with gr.Row():
|
| 184 |
+
temp = gr.Slider(280, 330, value=300, label="Temperature (K)")
|
| 185 |
+
temp_unit = gr.Dropdown(["K", "°C", "°F"], value="K", label="", scale=0.2)
|
| 186 |
+
|
| 187 |
+
temp_unit.change(fn=update_temp_slider, inputs=temp_unit, outputs=temp)
|
| 188 |
+
|
| 189 |
+
with gr.Row():
|
| 190 |
+
humidity = gr.Slider(0, 100, value=30, label="Humidity (%)")
|
| 191 |
+
gr.Dropdown(["%"], value="%", label="", scale=0.1)
|
| 192 |
+
|
| 193 |
+
with gr.Row():
|
| 194 |
+
wind_speed = gr.Slider(0, 50, value=10, label="Wind Speed (m/s)")
|
| 195 |
+
wind_unit = gr.Dropdown(["m/s", "km/h", "mp/h"], value="m/s", label="", scale=0.2)
|
| 196 |
+
|
| 197 |
+
wind_unit.change(update_wind_slider, inputs=wind_unit, outputs=wind_speed)
|
| 198 |
+
|
| 199 |
+
with gr.Row():
|
| 200 |
+
elevation = gr.Slider(0, 3000, value=500, label="Elevation (m)")
|
| 201 |
+
elev_unit = gr.Dropdown(["m", "ft"], value="m", label="", scale=0.2)
|
| 202 |
+
|
| 203 |
+
elev_unit.change(update_elevation_slider, inputs=elev_unit, outputs=elevation)
|
| 204 |
+
|
| 205 |
+
with gr.Row():
|
| 206 |
+
vegetation_index = gr.Slider(0.0, 2.0, value=1.0, label="Vegetation Index (NDVI)")
|
| 207 |
+
gr.Dropdown(["NDVI"], value="NDVI", label="", scale=0.2)
|
| 208 |
+
use_trust = gr.Checkbox(label="Use FireTrustNet", value=True)
|
| 209 |
+
sweep_axis = gr.Radio(["temperature", "humidity", "wind_speed", "vegetation_index", "elevation"],
|
| 210 |
+
label="Sweep Axis", value="temperature")
|
| 211 |
+
predict_btn = gr.Button("Predict")
|
| 212 |
+
with gr.Column():
|
| 213 |
+
with gr.Accordion("ℹ️ Feature Definitions", open=False):
|
| 214 |
+
gr.Markdown("""
|
| 215 |
+
**Temperaure:** Current Temperature
|
| 216 |
+
|
| 217 |
+
**Humidity:** Current Humidity
|
| 218 |
+
|
| 219 |
+
**Wind Speed:** Current Wind Speed
|
| 220 |
+
|
| 221 |
+
**Elevation:** Current Elevation Relative to Sea Level
|
| 222 |
+
|
| 223 |
+
**Vegitation Index:** Your area's NDVI score.
|
| 224 |
+
""")
|
| 225 |
+
output = gr.Textbox(label="Result")
|
| 226 |
+
plot_output = gr.Plot(label="Trust Modulation Plot")
|
| 227 |
+
|
| 228 |
+
predict_btn.click(
|
| 229 |
+
fn=lambda t, tu, h, w, wu, v, e, eu, trust, axis: (
|
| 230 |
+
predict_fire(t, tu, h, w, wu, v, e, eu, trust),
|
| 231 |
+
generate_plot(axis, trust)
|
| 232 |
+
),
|
| 233 |
+
inputs=[
|
| 234 |
+
temp, temp_unit,
|
| 235 |
+
humidity,
|
| 236 |
+
wind_speed, wind_unit,
|
| 237 |
+
vegetation_index,
|
| 238 |
+
elevation, elev_unit,
|
| 239 |
+
use_trust,
|
| 240 |
+
sweep_axis
|
| 241 |
+
],
|
| 242 |
+
outputs=[output, plot_output]
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
with gr.Tab("🏞️ FV-FloodNet"):
|
| 246 |
+
with gr.Row():
|
| 247 |
+
with gr.Column():
|
| 248 |
+
with gr.Row():
|
| 249 |
+
rainfall = gr.Slider(0, 200, value=50, label="Rainfall (mm)")
|
| 250 |
+
rainfall_unit = gr.Dropdown(["mm", "in"], value="mm", label="", scale=0.2)
|
| 251 |
+
|
| 252 |
+
with gr.Row():
|
| 253 |
+
water_level = gr.Slider(0, 8000, value=3000, label="Relative Water Level (mm)")
|
| 254 |
+
gr.Dropdown(["mm"], value="mm", label="", scale=0.2)
|
| 255 |
+
|
| 256 |
+
with gr.Row():
|
| 257 |
+
elevation_flood = gr.Slider(0, 20, value=5, label="Relative Elevation (m)")
|
| 258 |
+
elev_flood_unit = gr.Dropdown(["m", "ft"], value="m", label="", scale=0.2)
|
| 259 |
+
|
| 260 |
+
with gr.Row():
|
| 261 |
+
slope = gr.Slider(0.0, 20.0, value=2.0, label="Slope (°)")
|
| 262 |
+
gr.Dropdown(["°"], label="",scale=0.2)
|
| 263 |
+
with gr.Row():
|
| 264 |
+
distance = gr.Slider(0, 2000, value=100, label="Distance from River (m)")
|
| 265 |
+
distance_unit = gr.Dropdown(["m", "ft"], value="m", label="", scale=0.2)
|
| 266 |
+
|
| 267 |
+
elev_flood_unit.change(update_flood_elevation_slider, inputs=elev_flood_unit, outputs=elevation_flood)
|
| 268 |
+
distance_unit.change(update_flood_distance_slider, inputs=distance_unit, outputs=distance)
|
| 269 |
+
rainfall_unit.change(update_flood_rainfall_slider, inputs=rainfall_unit, outputs=rainfall)
|
| 270 |
+
use_trust_flood = gr.Checkbox(label="Use FV-FloodTrustNet", value=True)
|
| 271 |
+
|
| 272 |
+
flood_sweep_axis = gr.Radio(
|
| 273 |
+
["rainfall", "water_level", "elevation", "slope", "distance_from_river"],
|
| 274 |
+
label="Sweep Axis", value="rainfall"
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
predict_btn_flood = gr.Button("Predict")
|
| 278 |
+
|
| 279 |
+
with gr.Column():
|
| 280 |
+
with gr.Accordion("ℹ️ Feature Definitions", open=False):
|
| 281 |
+
gr.Markdown("""
|
| 282 |
+
**Rainfall:** Total recent precipitation - Last 24 hours.
|
| 283 |
+
|
| 284 |
+
**Relative Water Level:** Height of river assuming river is 2.5m (8.202 ft) deep. Adjust accordingly.
|
| 285 |
+
|
| 286 |
+
**Relative Elevation:** Ground height relative to nearest body of water (river).
|
| 287 |
+
|
| 288 |
+
**Slope:** Terrain gradient measured in degrees.
|
| 289 |
+
|
| 290 |
+
**Distance from River:** Horizontal distance from riverbed in meters. This does not account for levees or terrain barriers.
|
| 291 |
+
""")
|
| 292 |
+
|
| 293 |
+
flood_output = gr.Textbox(label="Flood Risk")
|
| 294 |
+
flood_plot = gr.Plot(label="Trust Modulation Plot")
|
| 295 |
+
|
| 296 |
+
predict_btn_flood.click(
|
| 297 |
+
fn=lambda r, ru, wl, e, eu, s, d, du, trust, axis: (
|
| 298 |
+
predict_flood(r, ru, wl, e, eu, s, d, du, trust),
|
| 299 |
+
generate_flood_plot(axis, trust)
|
| 300 |
+
),
|
| 301 |
+
inputs=[
|
| 302 |
+
rainfall, rainfall_unit,
|
| 303 |
+
water_level,
|
| 304 |
+
elevation_flood, elev_flood_unit,
|
| 305 |
+
slope,
|
| 306 |
+
distance, distance_unit,
|
| 307 |
+
use_trust_flood,
|
| 308 |
+
flood_sweep_axis
|
| 309 |
+
],
|
| 310 |
+
outputs=[flood_output, flood_plot]
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
app = FastAPI()
|
| 314 |
+
|
| 315 |
+
app.add_middleware(
|
| 316 |
+
CORSMiddleware,
|
| 317 |
+
allow_origins=["*"],
|
| 318 |
+
allow_methods=["*"],
|
| 319 |
+
allow_headers=["*"],
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|
| 323 |
+
|
| 324 |
+
@app.get("/api/status")
|
| 325 |
+
def hello():
|
| 326 |
+
return JSONResponse({"status": "ok"})
|