aaradhya233's picture
Upload app.py
19355c9 verified
Raw
History Blame Contribute Delete
5.26 kB
import gradio as gr
import pickle
import numpy as np
import requests
# Load new model
with open('fire_rf_model_v2.pkl', 'rb') as f:
model = pickle.load(f)
def get_real_weather(lat, lon):
"""Fetch real ERA5 weather from Open-Meteo"""
url = (
f"https://archive-api.open-meteo.com/v1/archive"
f"?latitude={lat}&longitude={lon}"
f"&start_date=2023-03-08&end_date=2023-03-08"
f"&daily=temperature_2m_max,precipitation_sum,"
f"windspeed_10m_max,dewpoint_2m_mean"
f"&timezone=Asia/Kolkata"
)
try:
r = requests.get(url, timeout=10)
d = r.json().get('daily', {})
temp = d.get('temperature_2m_max', [None])[0]
precip = d.get('precipitation_sum', [None])[0]
wind = d.get('windspeed_10m_max', [None])[0]
dew = d.get('dewpoint_2m_mean', [None])[0]
humidity = round(100 * np.exp(17.625*dew/(243.04+dew)) /
np.exp(17.625*temp/(243.04+temp)), 1) if dew and temp else 60.0
return temp or 25.0, precip or 5.0, wind or 12.0, humidity
except:
return 25.0, 5.0, 12.0, 60.0
def predict_fire_risk(latitude, longitude, ndvi, aod, elevation,
drought_index, land_cover):
land_cover_map = {'Forest': 0, 'Grassland': 1,
'Agricultural': 2, 'Shrubland': 3}
# Auto-fetch real ERA5 weather
temperature, precipitation, wind_speed, humidity = get_real_weather(
round(latitude, 2), round(longitude, 2)
)
features = np.array([[
temperature, precipitation, wind_speed, humidity,
ndvi, aod, elevation, drought_index,
land_cover_map[land_cover]
]])
prob = model.predict_proba(features)[0][1]
risk_pct = prob * 100
if prob >= 0.80:
level = "πŸ”΄ CRITICAL FIRE RISK"
color = "background-color: #ff4444; color: white; padding: 20px; border-radius: 10px; font-size: 20px; font-weight: bold;"
elif prob >= 0.60:
level = "🟠 HIGH FIRE RISK"
color = "background-color: #ff8800; color: white; padding: 20px; border-radius: 10px; font-size: 20px; font-weight: bold;"
elif prob >= 0.40:
level = "🟑 MODERATE FIRE RISK"
color = "background-color: #ffcc00; color: black; padding: 20px; border-radius: 10px; font-size: 20px; font-weight: bold;"
else:
level = "🟒 LOW FIRE RISK"
color = "background-color: #44bb44; color: white; padding: 20px; border-radius: 10px; font-size: 20px; font-weight: bold;"
result = f"""
**{level}**
**Fire Probability: {risk_pct:.1f}%**
---
### 🌀️ ERA5 Weather (Auto-fetched via Open-Meteo)
| Parameter | Value |
|-----------|-------|
| 🌑️ Temperature | {temperature:.1f}°C |
| 🌧️ Precipitation | {precipitation:.1f} mm |
| πŸ’¨ Wind Speed | {wind_speed:.1f} km/h |
| πŸ’§ Humidity | {humidity:.1f}% |
---
### 🌿 Vegetation & Terrain Inputs
| Parameter | Value |
|-----------|-------|
| NDVI | {ndvi:.2f} |
| AOD | {aod:.2f} |
| Elevation | {elevation:.0f} m |
| Drought Index | {drought_index:.2f} |
| Land Cover | {land_cover} |
---
*Model: Random Forest | AUC: 0.9583 | Weather: ERA5 Reanalysis via Open-Meteo*
*Data fusion: NASA FIRMS MODIS + ERA5 atmospheric reanalysis*
"""
return result
# Build UI
with gr.Blocks(title="AirSense Fire Risk β€” ERA5 Fusion", theme=gr.themes.Soft()) as app:
gr.Markdown("""
# πŸ”₯ AirSense β€” Forest Fire Risk Prediction
### Northeast India | ERA5 Weather Data Fusion
**Enter coordinates and vegetation parameters β€” real atmospheric data is fetched automatically from ERA5 reanalysis.**
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### πŸ“ Location")
latitude = gr.Slider(21.5, 29.5, value=26.5, step=0.1, label="Latitude")
longitude = gr.Slider(88.5, 95.5, value=93.5, step=0.1, label="Longitude")
gr.Markdown("### 🌿 Vegetation & Terrain")
ndvi = gr.Slider(0.0, 1.0, value=0.4, step=0.01, label="NDVI (Vegetation Index)")
aod = gr.Slider(0.0, 1.5, value=0.4, step=0.01, label="AOD (Aerosol Optical Depth)")
elevation = gr.Slider(0, 3000, value=400, step=10, label="Elevation (m)")
drought_index = gr.Slider(-2.0, 2.0, value=0.5, step=0.1, label="Drought Index")
land_cover = gr.Dropdown(
['Forest', 'Grassland', 'Agricultural', 'Shrubland'],
value='Forest', label="Land Cover Type"
)
predict_btn = gr.Button("πŸ” Predict Fire Risk", variant="primary", size="lg")
with gr.Column(scale=1):
gr.Markdown("### πŸ“Š Prediction Results")
output = gr.Markdown(value="*Adjust parameters and click Predict*")
predict_btn.click(
fn=predict_fire_risk,
inputs=[latitude, longitude, ndvi, aod, elevation, drought_index, land_cover],
outputs=output
)
gr.Markdown("""
---
**Data Sources:** NASA FIRMS MODIS (fire detections) β€’ ERA5 Reanalysis via Open-Meteo (weather)
**Model:** Random Forest Classifier | Trained on 60 presence-absence points | AUC: 0.9583
**Region:** Northeast India (21.5Β°N–29.5Β°N, 88.5Β°E–95.5Β°E)
""")
app.launch()