Update app.py
Browse files
app.py
CHANGED
|
@@ -1,73 +1,171 @@
|
|
| 1 |
-
# Step 2: Import Necessary Libraries
|
| 2 |
-
import os
|
| 3 |
import numpy as np
|
| 4 |
-
import rasterio
|
| 5 |
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from tensorflow.keras import layers, Model
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
import gradio as gr
|
| 10 |
-
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
conv1 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(conv1)
|
| 21 |
-
pool1 = layers.MaxPooling2D((2, 2))(conv1)
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
conv5 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(conv5)
|
| 39 |
|
| 40 |
-
outputs = layers.Conv2D(1, (1, 1), activation='sigmoid')(
|
| 41 |
return Model(inputs, outputs)
|
| 42 |
|
| 43 |
-
#
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
#
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
fn=predict_flood,
|
| 65 |
-
inputs=
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
| 67 |
title="Flood Risk Prediction",
|
| 68 |
-
description="Upload
|
| 69 |
)
|
| 70 |
|
| 71 |
-
|
| 72 |
-
# Step 8: Launch the Gradio App
|
| 73 |
-
interface.launch()
|
|
|
|
|
|
|
|
|
|
| 1 |
import numpy as np
|
|
|
|
| 2 |
import matplotlib.pyplot as plt
|
| 3 |
+
import os
|
| 4 |
+
from sklearn.model_selection import train_test_split
|
| 5 |
+
|
| 6 |
+
# Generate synthetic terrain and rainfall data
|
| 7 |
+
def generate_data(num_samples=100, img_size=128):
|
| 8 |
+
X = [] # Input data: terrain maps
|
| 9 |
+
Y = [] # Output data: flood risk maps
|
| 10 |
+
for _ in range(num_samples):
|
| 11 |
+
# Generate synthetic terrain (random elevation patterns)
|
| 12 |
+
terrain = np.random.rand(img_size, img_size)
|
| 13 |
+
|
| 14 |
+
# Generate rainfall patterns
|
| 15 |
+
rainfall = np.random.rand(img_size, img_size) * 0.5
|
| 16 |
+
|
| 17 |
+
# Combine terrain and rainfall to simulate flood risk
|
| 18 |
+
flood_risk = np.clip(terrain + rainfall, 0, 1)
|
| 19 |
+
|
| 20 |
+
X.append(np.dstack([terrain, rainfall])) # Stack terrain + rainfall as input channels
|
| 21 |
+
Y.append(flood_risk) # Flood risk map as output
|
| 22 |
+
|
| 23 |
+
X = np.array(X)
|
| 24 |
+
Y = np.array(Y)
|
| 25 |
+
return X, Y
|
| 26 |
+
|
| 27 |
+
# Generate data
|
| 28 |
+
X, Y = generate_data(200)
|
| 29 |
+
|
| 30 |
+
# Split data into training and testing sets
|
| 31 |
+
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
import tensorflow as tf
|
| 35 |
from tensorflow.keras import layers, Model
|
| 36 |
+
|
| 37 |
+
# Define the UNet model
|
| 38 |
+
def unet_model(input_shape=(128, 128, 2)):
|
| 39 |
+
inputs = layers.Input(shape=input_shape)
|
| 40 |
+
|
| 41 |
+
# Encoder
|
| 42 |
+
c1 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(inputs)
|
| 43 |
+
c1 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(c1)
|
| 44 |
+
p1 = layers.MaxPooling2D((2, 2))(c1)
|
| 45 |
+
|
| 46 |
+
c2 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(p1)
|
| 47 |
+
c2 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(c2)
|
| 48 |
+
p2 = layers.MaxPooling2D((2, 2))(c2)
|
| 49 |
+
|
| 50 |
+
# Bottleneck
|
| 51 |
+
b = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(p2)
|
| 52 |
+
b = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(b)
|
| 53 |
+
|
| 54 |
+
# Decoder
|
| 55 |
+
u2 = layers.UpSampling2D((2, 2))(b)
|
| 56 |
+
c3 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(u2)
|
| 57 |
+
c3 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(c3)
|
| 58 |
+
|
| 59 |
+
u1 = layers.UpSampling2D((2, 2))(c3)
|
| 60 |
+
c4 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(u1)
|
| 61 |
+
c4 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(c4)
|
| 62 |
+
|
| 63 |
+
outputs = layers.Conv2D(1, (1, 1), activation='sigmoid')(c4)
|
| 64 |
+
return Model(inputs, outputs)
|
| 65 |
+
|
| 66 |
+
# Compile the model
|
| 67 |
+
model = unet_model()
|
| 68 |
+
model.compile(optimizer='adam', loss='mse', metrics=['accuracy'])
|
| 69 |
+
model.summary()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# Train the model
|
| 73 |
+
history = model.fit(X_train, Y_train, epochs=10, batch_size=16, validation_data=(X_test, Y_test))
|
| 74 |
+
|
| 75 |
+
import numpy as np
|
| 76 |
import gradio as gr
|
| 77 |
+
import tensorflow as tf
|
| 78 |
+
from tensorflow.keras import layers, Model
|
| 79 |
|
| 80 |
+
# Define the UNet model
|
| 81 |
+
def unet_model(input_shape=(128, 128, 2)):
|
| 82 |
+
inputs = layers.Input(shape=input_shape)
|
| 83 |
|
| 84 |
+
# Encoder
|
| 85 |
+
c1 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(inputs)
|
| 86 |
+
c1 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(c1)
|
| 87 |
+
p1 = layers.MaxPooling2D((2, 2))(c1)
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
c2 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(p1)
|
| 90 |
+
c2 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(c2)
|
| 91 |
+
p2 = layers.MaxPooling2D((2, 2))(c2)
|
| 92 |
|
| 93 |
+
# Bottleneck
|
| 94 |
+
b = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(p2)
|
| 95 |
+
b = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(b)
|
| 96 |
|
| 97 |
+
# Decoder
|
| 98 |
+
u2 = layers.UpSampling2D((2, 2))(b)
|
| 99 |
+
c3 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(u2)
|
| 100 |
+
c3 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(c3)
|
| 101 |
|
| 102 |
+
u1 = layers.UpSampling2D((2, 2))(c3)
|
| 103 |
+
c4 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(u1)
|
| 104 |
+
c4 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(c4)
|
|
|
|
| 105 |
|
| 106 |
+
outputs = layers.Conv2D(1, (1, 1), activation='sigmoid')(c4)
|
| 107 |
return Model(inputs, outputs)
|
| 108 |
|
| 109 |
+
# Create and compile the model
|
| 110 |
+
model = unet_model()
|
| 111 |
+
model.compile(optimizer='adam', loss='mse', metrics=['accuracy'])
|
| 112 |
+
|
| 113 |
+
# Gradio function for prediction with proper error handling
|
| 114 |
+
def predict_flood(terrain, rainfall):
|
| 115 |
+
try:
|
| 116 |
+
# Ensure the inputs are numpy arrays
|
| 117 |
+
if not isinstance(terrain, np.ndarray) or not isinstance(rainfall, np.ndarray):
|
| 118 |
+
raise ValueError("Both terrain and rainfall must be NumPy arrays.")
|
| 119 |
+
|
| 120 |
+
# Check if the input images are of correct shape
|
| 121 |
+
if terrain.shape != (128, 128) or rainfall.shape != (128, 128):
|
| 122 |
+
raise ValueError("Both terrain and rainfall images must be of shape (128, 128).")
|
| 123 |
+
|
| 124 |
+
# Normalize the images to [0, 1]
|
| 125 |
+
terrain = terrain.astype(np.float32) / 255.0
|
| 126 |
+
rainfall = rainfall.astype(np.float32) / 255.0
|
| 127 |
+
|
| 128 |
+
# Stack terrain and rainfall into a 2-channel input (128x128x2)
|
| 129 |
+
input_data = np.dstack([terrain, rainfall]) # Shape: (128, 128, 2)
|
| 130 |
+
input_data = input_data.reshape(1, 128, 128, 2) # Shape: (1, 128, 128, 2)
|
| 131 |
+
|
| 132 |
+
# Debug: Print input data shape and min/max values
|
| 133 |
+
print(f"Input data shape: {input_data.shape}")
|
| 134 |
+
print(f"Terrain min/max: {terrain.min()}/{terrain.max()}")
|
| 135 |
+
print(f"Rainfall min/max: {rainfall.min()}/{rainfall.max()}")
|
| 136 |
+
|
| 137 |
+
# Make prediction using the model
|
| 138 |
+
prediction = model.predict(input_data)[0].squeeze() # Get the first prediction
|
| 139 |
+
|
| 140 |
+
# Debug: Print prediction shape and min/max values
|
| 141 |
+
print(f"Prediction shape: {prediction.shape}")
|
| 142 |
+
print(f"Prediction min/max: {prediction.min()}/{prediction.max()}")
|
| 143 |
+
|
| 144 |
+
# Check if prediction is in expected range
|
| 145 |
+
if prediction.shape != (128, 128):
|
| 146 |
+
raise ValueError("Model output is not of expected shape (128, 128).")
|
| 147 |
+
|
| 148 |
+
# Rescale prediction to range [0, 255] for image output
|
| 149 |
+
prediction = (prediction * 255).astype(np.uint8) # Convert prediction to uint8 for display
|
| 150 |
+
|
| 151 |
+
return prediction
|
| 152 |
+
|
| 153 |
+
except Exception as e:
|
| 154 |
+
# Handle any exceptions and print the error
|
| 155 |
+
print(f"Error during prediction: {e}")
|
| 156 |
+
# Return a black image in case of error (debugging step)
|
| 157 |
+
return np.zeros((128, 128), dtype=np.uint8)
|
| 158 |
+
|
| 159 |
+
# Launch Gradio app with error handling in place
|
| 160 |
+
iface = gr.Interface(
|
| 161 |
fn=predict_flood,
|
| 162 |
+
inputs=[
|
| 163 |
+
gr.Image(type="numpy", label="Terrain Map", image_mode='L'), # Input: Terrain Map (grayscale)
|
| 164 |
+
gr.Image(type="numpy", label="Rainfall Map", image_mode='L') # Input: Rainfall Map (grayscale)
|
| 165 |
+
],
|
| 166 |
+
outputs=gr.Image(label="Predicted Flood Risk Map", type="numpy"), # Output: Flood Risk Map
|
| 167 |
title="Flood Risk Prediction",
|
| 168 |
+
description="Upload terrain and rainfall maps to predict flood risk."
|
| 169 |
)
|
| 170 |
|
| 171 |
+
iface.launch()
|
|
|
|
|
|