ArshadNawaz123 commited on
Commit
06e9ccf
·
verified ·
1 Parent(s): 2376c13

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -56
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
- from tensorflow.keras.models import load_model
8
- from groq import Groq
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  import gradio as gr
10
- from PIL import Image
 
11
 
12
- # Step 3: Set Up Groq API
13
- os.environ['GROQ_API_KEY'] = 'secretName'
14
- client = Groq(api_key=os.getenv('GROQ_API_KEY'))
15
 
16
- # Step 4: Define the UNet Model
17
- def build_unet(input_shape):
18
- inputs = layers.Input(input_shape)
19
- conv1 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(inputs)
20
- conv1 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(conv1)
21
- pool1 = layers.MaxPooling2D((2, 2))(conv1)
22
 
23
- conv2 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(pool1)
24
- conv2 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(conv2)
25
- pool2 = layers.MaxPooling2D((2, 2))(conv2)
26
 
27
- conv3 = layers.Conv2D(256, (3, 3), activation='relu', padding='same')(pool2)
28
- conv3 = layers.Conv2D(256, (3, 3), activation='relu', padding='same')(conv3)
 
29
 
30
- up1 = layers.Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv3)
31
- merge1 = layers.concatenate([conv2, up1], axis=-1)
32
- conv4 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(merge1)
33
- conv4 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(conv4)
34
 
35
- up2 = layers.Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv4)
36
- merge2 = layers.concatenate([conv1, up2], axis=-1)
37
- conv5 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(merge2)
38
- conv5 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(conv5)
39
 
40
- outputs = layers.Conv2D(1, (1, 1), activation='sigmoid')(conv5)
41
  return Model(inputs, outputs)
42
 
43
- # Step 5: Train the UNet Model
44
- input_shape = (128, 128, 1)
45
- X_train = np.random.rand(100, *input_shape)
46
- y_train = np.random.rand(100, *input_shape)
47
-
48
- model = build_unet(input_shape)
49
- model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
50
- model.fit(X_train, y_train, epochs=5, batch_size=8)
51
- model.save("flood_risk_model.h5")
52
-
53
- # Step 6: Define Flood Prediction Function
54
- def predict_flood(input_image):
55
- input_image = Image.fromarray(input_image).convert("L").resize((128, 128))
56
- input_image = np.array(input_image) / 255.0
57
- input_image = np.expand_dims(input_image, axis=(0, -1))
58
- model = load_model("flood_risk_model.h5")
59
- prediction = model.predict(input_image).squeeze()
60
- return prediction
61
-
62
- # Step 7: Create Gradio Interface
63
- interface = gr.Interface(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  fn=predict_flood,
65
- inputs=gr.Image(image_mode="L"), # Removed 'tool'
66
- outputs=gr.Image(label="Predicted Flood Risk"),
 
 
 
67
  title="Flood Risk Prediction",
68
- description="Upload a terrain DEM image to predict flood risks. Images will be resized to 128x128 automatically."
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()