Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,165 +1,165 @@
|
|
| 1 |
-
import pandas as pd
|
| 2 |
-
import numpy as np
|
| 3 |
-
import matplotlib.pyplot as plt
|
| 4 |
-
from matplotlib import image
|
| 5 |
-
plt.style.use("fivethirtyeight")
|
| 6 |
-
import PIL
|
| 7 |
-
from PIL import Image, ImageFile
|
| 8 |
-
import os, shutil
|
| 9 |
-
from tqdm.auto import tqdm, trange
|
| 10 |
-
import gradio as gr
|
| 11 |
-
|
| 12 |
-
import torch, torchvision
|
| 13 |
-
import torch.nn as nn
|
| 14 |
-
from torchvision.transforms import v2 as v2
|
| 15 |
-
import lightning.pytorch as pl
|
| 16 |
-
from lightning.pytorch import LightningModule, LightningDataModule
|
| 17 |
-
import tempfile
|
| 18 |
-
|
| 19 |
-
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 20 |
-
|
| 21 |
-
import utils
|
| 22 |
-
from utils.utils import prepare_image, make_preds_return_mask, load_model, get_gt
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def run_gradio_app():
|
| 26 |
-
def process_image(img_path_):
|
| 27 |
-
lightning_model = load_model()
|
| 28 |
-
image = prepare_image(path=img_path_)
|
| 29 |
-
mask_array = make_preds_return_mask(img=image, model=lightning_model) # return numpy
|
| 30 |
-
gt_array = np.array(get_gt(img_path_))
|
| 31 |
-
|
| 32 |
-
# Visualization
|
| 33 |
-
gt_pil = Image.fromarray(
|
| 34 |
-
mask_pil = Image.fromarray((mask_array * 255.0).astype(np.uint8)).resize((
|
| 35 |
-
|
| 36 |
-
# Flood ratio
|
| 37 |
-
flood_pixels = np.sum(mask_array > 0.5)
|
| 38 |
-
total_pixels = mask_array.size
|
| 39 |
-
flood_ratio = flood_pixels / total_pixels
|
| 40 |
-
if flood_ratio > 0.05:
|
| 41 |
-
status_text = (
|
| 42 |
-
f"Flood detected in approximately {flood_ratio*100:.2f}% of the area.\n\n"
|
| 43 |
-
"π Recommended Actions for Urban Planners:\n"
|
| 44 |
-
"- Prioritize evacuation and relief efforts in the most affected zones.\n"
|
| 45 |
-
"- Assess drainage and waterway capacity; reinforce weak infrastructure.\n"
|
| 46 |
-
"- Deploy flood barriers or temporary defenses where feasible.\n"
|
| 47 |
-
"- Coordinate with emergency services for rapid response.\n"
|
| 48 |
-
"- Use these flood maps for long-term planning: zoning, flood-resilient housing, "
|
| 49 |
-
"and sustainable water management strategies."
|
| 50 |
-
)
|
| 51 |
-
else:
|
| 52 |
-
status_text = (
|
| 53 |
-
"β οΈ No significant flooding detected.\n\n"
|
| 54 |
-
"π Recommendations:\n"
|
| 55 |
-
"- Continue monitoring the area, as conditions may change with rainfall.\n"
|
| 56 |
-
"- Maintain drainage systems to prevent localized flooding.\n"
|
| 57 |
-
"- Use this opportunity to strengthen flood preparedness measures "
|
| 58 |
-
"and update urban planning models with the latest satellite data."
|
| 59 |
-
)
|
| 60 |
-
|
| 61 |
-
# Save mask to temp file for download
|
| 62 |
-
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
|
| 63 |
-
mask_pil.save(temp_file.name)
|
| 64 |
-
|
| 65 |
-
return gt_pil, mask_pil, status_text, temp_file.name
|
| 66 |
-
|
| 67 |
-
title = "π Flood Detection & Mapping (Sentinel-1 & Sentinel-2)"
|
| 68 |
-
|
| 69 |
-
description = """
|
| 70 |
-
## π Automated Flood Mapping & Evaluation Platform
|
| 71 |
-
|
| 72 |
-
This platform leverages **Sentinel-2 satellite imagery** combined with a trained **UNet deep learning model**
|
| 73 |
-
to deliver high-resolution flood detection and mapping. The system is designed to support **urban planners,
|
| 74 |
-
emergency response teams, and environmental agencies** in making timely, data-driven decisions.
|
| 75 |
-
|
| 76 |
-
### π What the System Provides
|
| 77 |
-
- **Automated Processing** of raw satellite imagery to generate accurate flood masks.
|
| 78 |
-
- **Visual Insights** with side-by-side comparisons of **Ground Truth** and **Predicted Flood Masks**.
|
| 79 |
-
- **Quantitative Summaries** including the percentage of land area inundated.
|
| 80 |
-
- **Downloadable GIS-Ready Outputs** (flood masks) for integration into planning and analysis tools.
|
| 81 |
-
- **Scalable Utility** across disaster response, environmental monitoring, climate adaptation,
|
| 82 |
-
and risk assessment workflows.
|
| 83 |
-
|
| 84 |
-
### π οΈ How to Use
|
| 85 |
-
1. Upload a **Sentinel-2 TIFF image** (preferably cloud-free).
|
| 86 |
-
2. Let the model process and generate the predicted flood mask.
|
| 87 |
-
3. Review the **visual outputs and textual summary** to assess flood extent.
|
| 88 |
-
4. Download the mask for use in **GIS software** or further analysis.
|
| 89 |
-
|
| 90 |
-
β‘ *This tool bridges cutting-edge AI with remote sensing data to empower better decisions
|
| 91 |
-
for disaster management and long-term resilience planning.*
|
| 92 |
-
"""
|
| 93 |
-
|
| 94 |
-
description2 = """
|
| 95 |
-
### π Why This Matters
|
| 96 |
-
Flooding remains one of the most destructive natural disasters worldwide. Rapid, reliable detection
|
| 97 |
-
is essential for:
|
| 98 |
-
- Guiding **evacuation planning** and **emergency relief operations**.
|
| 99 |
-
- Supporting **sustainable urban development** through flood-resilient zoning.
|
| 100 |
-
- Enhancing **climate resilience strategies** for vulnerable regions.
|
| 101 |
-
"""
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
professional_theme = gr.themes.Base(
|
| 105 |
-
primary_hue="blue",
|
| 106 |
-
secondary_hue="slate",
|
| 107 |
-
).set(
|
| 108 |
-
button_primary_background_fill="linear-gradient(90deg, #0F4C75, #3282B8)",
|
| 109 |
-
button_primary_background_fill_hover="linear-gradient(90deg, #3282B8, #0F4C75)",
|
| 110 |
-
button_primary_text_color="white",
|
| 111 |
-
button_primary_shadow="0px 2px 6px rgba(0,0,0,0.15)",
|
| 112 |
-
block_title_text_color="#0F3057",
|
| 113 |
-
body_background_fill="#F8FAFC", # light gray background
|
| 114 |
-
block_background_fill="#FFFFFF", # white for content cards
|
| 115 |
-
block_shadow="0px 2px 6px rgba(0,0,0,0.1)",
|
| 116 |
-
border_color_primary="#D1D5DB",
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
# ----------------------------
|
| 120 |
-
# Gradio App Layout
|
| 121 |
-
# ----------------------------
|
| 122 |
-
with gr.Blocks(theme=professional_theme) as demo:
|
| 123 |
-
|
| 124 |
-
# ---- HEADER BAR ----
|
| 125 |
-
with gr.Row():
|
| 126 |
-
with gr.Column(scale = 1):
|
| 127 |
-
gr.Markdown(
|
| 128 |
-
f"<h1 style='color:#0F3057; margin-bottom:0'>Flood Detection & Mapping Platform</h1>"
|
| 129 |
-
"<p style='font-size:18px; color:#555;'>Powered by Sentinel-2 Imagery & Deep Learning</p>"
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
# ---- DESCRIPTION ----
|
| 133 |
-
gr.Markdown(description)
|
| 134 |
-
|
| 135 |
-
# ---- INPUT & STATUS ----
|
| 136 |
-
with gr.Row():
|
| 137 |
-
with gr.Column():
|
| 138 |
-
input_img = gr.File(file_types=["image"], label="Upload Sentinel Image")
|
| 139 |
-
run_btn = gr.Button("Run Flood Detection", variant="primary")
|
| 140 |
-
with gr.Column():
|
| 141 |
-
status_box = gr.Textbox(label="Detection Summary", interactive=False)
|
| 142 |
-
gr.Markdown(description2)
|
| 143 |
-
|
| 144 |
-
# ---- OUTPUT VISUALS ----
|
| 145 |
-
with gr.Row():
|
| 146 |
-
gt_out = gr.Image(type="pil", label="Ground Truth")
|
| 147 |
-
pred_out = gr.Image(type="pil", label="Predicted Flood Mask")
|
| 148 |
-
|
| 149 |
-
# ---- DOWNLOAD ----
|
| 150 |
-
with gr.Row():
|
| 151 |
-
download_mask = gr.File(label="Download Predicted Mask")
|
| 152 |
-
|
| 153 |
-
# ---- BUTTON ACTION ----
|
| 154 |
-
run_btn.click(
|
| 155 |
-
fn=process_image,
|
| 156 |
-
inputs=[input_img],
|
| 157 |
-
outputs=[gt_out, pred_out, status_box, download_mask]
|
| 158 |
-
)
|
| 159 |
-
# gr.Markdown(description2)
|
| 160 |
-
|
| 161 |
-
demo.launch(share=False)
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
if __name__ == "__main__":
|
| 165 |
run_gradio_app()
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from matplotlib import image
|
| 5 |
+
plt.style.use("fivethirtyeight")
|
| 6 |
+
import PIL
|
| 7 |
+
from PIL import Image, ImageFile
|
| 8 |
+
import os, shutil
|
| 9 |
+
from tqdm.auto import tqdm, trange
|
| 10 |
+
import gradio as gr
|
| 11 |
+
|
| 12 |
+
import torch, torchvision
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from torchvision.transforms import v2 as v2
|
| 15 |
+
import lightning.pytorch as pl
|
| 16 |
+
from lightning.pytorch import LightningModule, LightningDataModule
|
| 17 |
+
import tempfile
|
| 18 |
+
|
| 19 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 20 |
+
|
| 21 |
+
import utils
|
| 22 |
+
from utils.utils import prepare_image, make_preds_return_mask, load_model, get_gt
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def run_gradio_app():
|
| 26 |
+
def process_image(img_path_):
|
| 27 |
+
lightning_model = load_model()
|
| 28 |
+
image = prepare_image(path=img_path_)
|
| 29 |
+
mask_array = make_preds_return_mask(img=image, model=lightning_model) # return numpy
|
| 30 |
+
gt_array = np.array(get_gt(img_path_))
|
| 31 |
+
|
| 32 |
+
# Visualization
|
| 33 |
+
gt_pil = Image.fromarray(gt_array).resize((500,500))
|
| 34 |
+
mask_pil = Image.fromarray((mask_array * 255.0).astype(np.uint8)).resize((500,500))
|
| 35 |
+
|
| 36 |
+
# Flood ratio
|
| 37 |
+
flood_pixels = np.sum(mask_array > 0.5)
|
| 38 |
+
total_pixels = mask_array.size
|
| 39 |
+
flood_ratio = flood_pixels / total_pixels
|
| 40 |
+
if flood_ratio > 0.05:
|
| 41 |
+
status_text = (
|
| 42 |
+
f"Flood detected in approximately {flood_ratio*100:.2f}% of the area.\n\n"
|
| 43 |
+
"π Recommended Actions for Urban Planners:\n"
|
| 44 |
+
"- Prioritize evacuation and relief efforts in the most affected zones.\n"
|
| 45 |
+
"- Assess drainage and waterway capacity; reinforce weak infrastructure.\n"
|
| 46 |
+
"- Deploy flood barriers or temporary defenses where feasible.\n"
|
| 47 |
+
"- Coordinate with emergency services for rapid response.\n"
|
| 48 |
+
"- Use these flood maps for long-term planning: zoning, flood-resilient housing, "
|
| 49 |
+
"and sustainable water management strategies."
|
| 50 |
+
)
|
| 51 |
+
else:
|
| 52 |
+
status_text = (
|
| 53 |
+
"β οΈ No significant flooding detected.\n\n"
|
| 54 |
+
"π Recommendations:\n"
|
| 55 |
+
"- Continue monitoring the area, as conditions may change with rainfall.\n"
|
| 56 |
+
"- Maintain drainage systems to prevent localized flooding.\n"
|
| 57 |
+
"- Use this opportunity to strengthen flood preparedness measures "
|
| 58 |
+
"and update urban planning models with the latest satellite data."
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Save mask to temp file for download
|
| 62 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
|
| 63 |
+
mask_pil.save(temp_file.name)
|
| 64 |
+
|
| 65 |
+
return gt_pil, mask_pil, status_text, temp_file.name
|
| 66 |
+
|
| 67 |
+
title = "π Flood Detection & Mapping (Sentinel-1 & Sentinel-2)"
|
| 68 |
+
|
| 69 |
+
description = """
|
| 70 |
+
## π Automated Flood Mapping & Evaluation Platform
|
| 71 |
+
|
| 72 |
+
This platform leverages **Sentinel-2 satellite imagery** combined with a trained **UNet deep learning model**
|
| 73 |
+
to deliver high-resolution flood detection and mapping. The system is designed to support **urban planners,
|
| 74 |
+
emergency response teams, and environmental agencies** in making timely, data-driven decisions.
|
| 75 |
+
|
| 76 |
+
### π What the System Provides
|
| 77 |
+
- **Automated Processing** of raw satellite imagery to generate accurate flood masks.
|
| 78 |
+
- **Visual Insights** with side-by-side comparisons of **Ground Truth** and **Predicted Flood Masks**.
|
| 79 |
+
- **Quantitative Summaries** including the percentage of land area inundated.
|
| 80 |
+
- **Downloadable GIS-Ready Outputs** (flood masks) for integration into planning and analysis tools.
|
| 81 |
+
- **Scalable Utility** across disaster response, environmental monitoring, climate adaptation,
|
| 82 |
+
and risk assessment workflows.
|
| 83 |
+
|
| 84 |
+
### π οΈ How to Use
|
| 85 |
+
1. Upload a **Sentinel-2 TIFF image** (preferably cloud-free).
|
| 86 |
+
2. Let the model process and generate the predicted flood mask.
|
| 87 |
+
3. Review the **visual outputs and textual summary** to assess flood extent.
|
| 88 |
+
4. Download the mask for use in **GIS software** or further analysis.
|
| 89 |
+
|
| 90 |
+
β‘ *This tool bridges cutting-edge AI with remote sensing data to empower better decisions
|
| 91 |
+
for disaster management and long-term resilience planning.*
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
description2 = """
|
| 95 |
+
### π Why This Matters
|
| 96 |
+
Flooding remains one of the most destructive natural disasters worldwide. Rapid, reliable detection
|
| 97 |
+
is essential for:
|
| 98 |
+
- Guiding **evacuation planning** and **emergency relief operations**.
|
| 99 |
+
- Supporting **sustainable urban development** through flood-resilient zoning.
|
| 100 |
+
- Enhancing **climate resilience strategies** for vulnerable regions.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
professional_theme = gr.themes.Base(
|
| 105 |
+
primary_hue="blue",
|
| 106 |
+
secondary_hue="slate",
|
| 107 |
+
).set(
|
| 108 |
+
button_primary_background_fill="linear-gradient(90deg, #0F4C75, #3282B8)",
|
| 109 |
+
button_primary_background_fill_hover="linear-gradient(90deg, #3282B8, #0F4C75)",
|
| 110 |
+
button_primary_text_color="white",
|
| 111 |
+
button_primary_shadow="0px 2px 6px rgba(0,0,0,0.15)",
|
| 112 |
+
block_title_text_color="#0F3057",
|
| 113 |
+
body_background_fill="#F8FAFC", # light gray background
|
| 114 |
+
block_background_fill="#FFFFFF", # white for content cards
|
| 115 |
+
block_shadow="0px 2px 6px rgba(0,0,0,0.1)",
|
| 116 |
+
border_color_primary="#D1D5DB",
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# ----------------------------
|
| 120 |
+
# Gradio App Layout
|
| 121 |
+
# ----------------------------
|
| 122 |
+
with gr.Blocks(theme=professional_theme) as demo:
|
| 123 |
+
|
| 124 |
+
# ---- HEADER BAR ----
|
| 125 |
+
with gr.Row():
|
| 126 |
+
with gr.Column(scale = 1):
|
| 127 |
+
gr.Markdown(
|
| 128 |
+
f"<h1 style='color:#0F3057; margin-bottom:0'>Flood Detection & Mapping Platform</h1>"
|
| 129 |
+
"<p style='font-size:18px; color:#555;'>Powered by Sentinel-2 Imagery & Deep Learning</p>"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# ---- DESCRIPTION ----
|
| 133 |
+
gr.Markdown(description)
|
| 134 |
+
|
| 135 |
+
# ---- INPUT & STATUS ----
|
| 136 |
+
with gr.Row():
|
| 137 |
+
with gr.Column():
|
| 138 |
+
input_img = gr.File(file_types=["image"], label="Upload Sentinel Image")
|
| 139 |
+
run_btn = gr.Button("Run Flood Detection", variant="primary")
|
| 140 |
+
with gr.Column():
|
| 141 |
+
status_box = gr.Textbox(label="Detection Summary", interactive=False)
|
| 142 |
+
gr.Markdown(description2)
|
| 143 |
+
|
| 144 |
+
# ---- OUTPUT VISUALS ----
|
| 145 |
+
with gr.Row():
|
| 146 |
+
gt_out = gr.Image(type="pil", label="Ground Truth")
|
| 147 |
+
pred_out = gr.Image(type="pil", label="Predicted Flood Mask")
|
| 148 |
+
|
| 149 |
+
# ---- DOWNLOAD ----
|
| 150 |
+
with gr.Row():
|
| 151 |
+
download_mask = gr.File(label="Download Predicted Mask")
|
| 152 |
+
|
| 153 |
+
# ---- BUTTON ACTION ----
|
| 154 |
+
run_btn.click(
|
| 155 |
+
fn=process_image,
|
| 156 |
+
inputs=[input_img],
|
| 157 |
+
outputs=[gt_out, pred_out, status_box, download_mask]
|
| 158 |
+
)
|
| 159 |
+
# gr.Markdown(description2)
|
| 160 |
+
|
| 161 |
+
demo.launch(share=False)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
if __name__ == "__main__":
|
| 165 |
run_gradio_app()
|