sanket09 commited on
Commit
015cdcd
·
verified ·
1 Parent(s): 03cfd4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +222 -27
app.py CHANGED
@@ -87,41 +87,236 @@ async def predict(file: UploadFile = File(...)):
87
  }
88
 
89
  # Optional: Serve the Gradio interface (if you still want to use it with FastAPI)
90
- def run_gradio_interface():
91
- func = partial(inference_on_file, model=model, custom_test_pipeline=custom_test_pipeline)
92
-
93
- with gr.Blocks() as demo:
94
- gr.Markdown(value='# Prithvi multi temporal crop classification')
95
- gr.Markdown(value='''Prithvi is a first-of-its-kind temporal Vision transformer pretrained by the IBM and NASA team on continental US Harmonised Landsat Sentinel 2 (HLS) data. This demo showcases how the model was finetuned to classify crop and other land use categories using multi temporal data. More details can be found [here](https://huggingface.co/ibm-nasa-geospatial/Prithvi-100M-multi-temporal-crop-classification).\n
96
- The user needs to provide an HLS geotiff image, including 18 bands for 3 time-step, and each time-step includes the channels described above (Blue, Green, Red, Narrow NIR, SWIR, SWIR 2) in order.''')
97
- with gr.Row():
98
- with gr.Column():
99
- inp = gr.File()
100
- btn = gr.Button("Submit")
101
-
102
- with gr.Row():
103
- inp1 = gr.Image(image_mode='RGB', scale=10, label='T1')
104
- inp2 = gr.Image(image_mode='RGB', scale=10, label='T2')
105
- inp3 = gr.Image(image_mode='RGB', scale=10, label='T3')
106
- out = gr.Image(image_mode='RGB', scale=10, label='Model prediction')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
- btn.click(fn=func, inputs=inp, outputs=[inp1, inp2, inp3, out])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
- with gr.Row():
111
- with gr.Column():
112
- gr.Examples(examples=["chip_102_345_merged.tif",
113
- "chip_104_104_merged.tif",
114
- "chip_109_421_merged.tif"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  inputs=inp,
116
  outputs=[inp1, inp2, inp3, out],
117
  preprocess=preprocess_example,
118
  fn=func,
119
  cache_examples=True)
120
- with gr.Column():
121
- gr.Markdown(value='### Model prediction legend')
122
- gr.Image(value='Legend.png', image_mode='RGB', show_label=False)
 
123
 
124
- demo.launch()
125
 
126
  if __name__ == "__main__":
127
  run_gradio_interface()
 
87
  }
88
 
89
  # Optional: Serve the Gradio interface (if you still want to use it with FastAPI)
90
+ cdl_color_map = [{'value': 1, 'label': 'Natural vegetation', 'rgb': (233,255,190)},
91
+ {'value': 2, 'label': 'Forest', 'rgb': (149,206,147)},
92
+ {'value': 3, 'label': 'Corn', 'rgb': (255,212,0)},
93
+ {'value': 4, 'label': 'Soybeans', 'rgb': (38,115,0)},
94
+ {'value': 5, 'label': 'Wetlands', 'rgb': (128,179,179)},
95
+ {'value': 6, 'label': 'Developed/Barren', 'rgb': (156,156,156)},
96
+ {'value': 7, 'label': 'Open Water', 'rgb': (77,112,163)},
97
+ {'value': 8, 'label': 'Winter Wheat', 'rgb': (168,112,0)},
98
+ {'value': 9, 'label': 'Alfalfa', 'rgb': (255,168,227)},
99
+ {'value': 10, 'label': 'Fallow/Idle cropland', 'rgb': (191,191,122)},
100
+ {'value': 11, 'label': 'Cotton', 'rgb':(255,38,38)},
101
+ {'value': 12, 'label': 'Sorghum', 'rgb':(255,158,15)},
102
+ {'value': 13, 'label': 'Other', 'rgb':(0,175,77)}]
103
+
104
+
105
+ def apply_color_map(rgb, color_map=cdl_color_map):
106
+
107
+
108
+ rgb_mapped = rgb.copy()
109
+
110
+ for map_tmp in cdl_color_map:
111
+
112
+ for i in range(3):
113
+ rgb_mapped[i] = np.where((rgb[0] == map_tmp['value']) & (rgb[1] == map_tmp['value']) & (rgb[2] == map_tmp['value']), map_tmp['rgb'][i], rgb_mapped[i])
114
+
115
+ return rgb_mapped
116
+
117
+
118
+ def stretch_rgb(rgb):
119
+
120
+ ls_pct=0
121
+ pLow, pHigh = np.percentile(rgb[~np.isnan(rgb)], (ls_pct,100-ls_pct))
122
+ img_rescale = exposure.rescale_intensity(rgb, in_range=(pLow,pHigh))
123
+
124
+ return img_rescale
125
+
126
+ def open_tiff(fname):
127
+
128
+ with rasterio.open(fname, "r") as src:
129
+
130
+ data = src.read()
131
+
132
+ return data
133
+
134
+ def write_tiff(img_wrt, filename, metadata):
135
+
136
+ """
137
+ It writes a raster image to file.
138
+
139
+ :param img_wrt: numpy array containing the data (can be 2D for single band or 3D for multiple bands)
140
+ :param filename: file path to the output file
141
+ :param metadata: metadata to use to write the raster to disk
142
+ :return:
143
+ """
144
+
145
+ with rasterio.open(filename, "w", **metadata) as dest:
146
+
147
+ if len(img_wrt.shape) == 2:
148
+
149
+ img_wrt = img_wrt[None]
150
+
151
+ for i in range(img_wrt.shape[0]):
152
+ dest.write(img_wrt[i, :, :], i + 1)
153
+
154
+ return filename
155
+
156
+
157
+ def get_meta(fname):
158
+
159
+ with rasterio.open(fname, "r") as src:
160
+
161
+ meta = src.meta
162
+
163
+ return meta
164
+
165
+ def preprocess_example(example_list):
166
+
167
+ example_list = [os.path.join(os.path.abspath(''), x) for x in example_list]
168
+
169
+ return example_list
170
+
171
+
172
+ def inference_segmentor(model, imgs, custom_test_pipeline=None):
173
+ """Inference image(s) with the segmentor.
174
+
175
+ Args:
176
+ model (nn.Module): The loaded segmentor.
177
+ imgs (str/ndarray or list[str/ndarray]): Either image files or loaded
178
+ images.
179
+
180
+ Returns:
181
+ (list[Tensor]): The segmentation result.
182
+ """
183
+ cfg = model.cfg
184
+ device = next(model.parameters()).device # model device
185
+ # build the data pipeline
186
+ test_pipeline = [LoadImageFromFile()] + cfg.data.test.pipeline[1:] if custom_test_pipeline == None else custom_test_pipeline
187
+ test_pipeline = Compose(test_pipeline)
188
+ # prepare data
189
+ data = []
190
+ imgs = imgs if isinstance(imgs, list) else [imgs]
191
+ for img in imgs:
192
+ img_data = {'img_info': {'filename': img}}
193
+ img_data = test_pipeline(img_data)
194
+ data.append(img_data)
195
+ # print(data.shape)
196
+
197
+ data = collate(data, samples_per_gpu=len(imgs))
198
+ if next(model.parameters()).is_cuda:
199
+ # data = collate(data, samples_per_gpu=len(imgs))
200
+ # scatter to specified GPU
201
+ data = scatter(data, [device])[0]
202
+ else:
203
+ # img_metas = scatter(data['img_metas'],'cpu')
204
+ # data['img_metas'] = [i.data[0] for i in data['img_metas']]
205
 
206
+ img_metas = data['img_metas'].data[0]
207
+ img = data['img']
208
+ data = {'img': img, 'img_metas':img_metas}
209
+
210
+ with torch.no_grad():
211
+ result = model(return_loss=False, rescale=True, **data)
212
+ return result
213
+
214
+
215
+ def process_rgb(input, mask, indexes):
216
+
217
+
218
+ rgb = stretch_rgb((input[indexes, :, :].transpose((1,2,0))/10000*255).astype(np.uint8))
219
+ rgb = np.where(mask.transpose((1,2,0)) == 1, 0, rgb)
220
+ rgb = np.where(rgb < 0, 0, rgb)
221
+ rgb = np.where(rgb > 255, 255, rgb)
222
+
223
+ return rgb
224
+
225
+ def inference_on_file(target_image, model, custom_test_pipeline):
226
+
227
+ target_image = target_image.name
228
+ time_taken=-1
229
+ st = time.time()
230
+ print('Running inference...')
231
+ result = inference_segmentor(model, target_image, custom_test_pipeline)
232
+ print("Output has shape: " + str(result[0].shape))
233
+
234
+ ##### get metadata mask
235
+ input = open_tiff(target_image)
236
+ meta = get_meta(target_image)
237
+ mask = np.where(input == meta['nodata'], 1, 0)
238
+ mask = np.max(mask, axis=0)[None]
239
+
240
+ rgb1 = process_rgb(input, mask, [2, 1, 0])
241
+ rgb2 = process_rgb(input, mask, [8, 7, 6])
242
+ rgb3 = process_rgb(input, mask, [14, 13, 12])
243
+
244
+ result[0] = np.where(mask == 1, 0, result[0])
245
+
246
+ et = time.time()
247
+ time_taken = np.round(et - st, 1)
248
+ print(f'Inference completed in {str(time_taken)} seconds')
249
+
250
+ output=result[0][0] + 1
251
+ output = np.vstack([output[None], output[None], output[None]]).astype(np.uint8)
252
+ output=apply_color_map(output).transpose((1,2,0))
253
 
254
+ return rgb1,rgb2,rgb3,output
255
+
256
+ def process_test_pipeline(custom_test_pipeline, bands=None):
257
+
258
+ # change extracted bands if necessary
259
+ if bands is not None:
260
+
261
+ extract_index = [i for i, x in enumerate(custom_test_pipeline) if x['type'] == 'BandsExtract' ]
262
+
263
+ if len(extract_index) > 0:
264
+
265
+ custom_test_pipeline[extract_index[0]]['bands'] = eval(bands)
266
+
267
+ collect_index = [i for i, x in enumerate(custom_test_pipeline) if x['type'].find('Collect') > -1]
268
+
269
+ # adapt collected keys if necessary
270
+ if len(collect_index) > 0:
271
+
272
+ keys = ['img_info', 'filename', 'ori_filename', 'img', 'img_shape', 'ori_shape', 'pad_shape', 'scale_factor', 'img_norm_cfg']
273
+ custom_test_pipeline[collect_index[0]]['meta_keys'] = keys
274
+
275
+ return custom_test_pipeline
276
+
277
+ config = Config.fromfile(config_path)
278
+ config.model.backbone.pretrained=None
279
+ model = init_segmentor(config, ckpt, device='cpu')
280
+ custom_test_pipeline=process_test_pipeline(model.cfg.data.test.pipeline, None)
281
+
282
+ func = partial(inference_on_file, model=model, custom_test_pipeline=custom_test_pipeline)
283
+
284
+ with gr.Blocks() as demo:
285
+
286
+ gr.Markdown(value='# Prithvi multi temporal crop classification')
287
+ gr.Markdown(value='''Prithvi is a first-of-its-kind temporal Vision transformer pretrained by the IBM and NASA team on continental US Harmonised Landsat Sentinel 2 (HLS) data. This demo showcases how the model was finetuned to classify crop and other land use categories using multi temporal data. More detailes can be found [here](https://huggingface.co/ibm-nasa-geospatial/Prithvi-100M-multi-temporal-crop-classification).\n
288
+ The user needs to provide an HLS geotiff image, including 18 bands for 3 time-step, and each time-step includes the channels described above (Blue, Green, Red, Narrow NIR, SWIR, SWIR 2) in order.
289
+ ''')
290
+ with gr.Row():
291
+ with gr.Column():
292
+ inp = gr.File()
293
+ btn = gr.Button("Submit")
294
+
295
+ with gr.Row():
296
+ inp1=gr.Image(image_mode='RGB', scale=10, label='T1')
297
+ inp2=gr.Image(image_mode='RGB', scale=10, label='T2')
298
+ inp3=gr.Image(image_mode='RGB', scale=10, label='T3')
299
+ out = gr.Image(image_mode='RGB', scale=10, label='Model prediction')
300
+ # gr.Image(value='Legend.png', image_mode='RGB', scale=2, show_label=False)
301
+
302
+ btn.click(fn=func, inputs=inp, outputs=[inp1, inp2, inp3, out])
303
+
304
+ with gr.Row():
305
+ with gr.Column():
306
+ gr.Examples(examples=["chip_102_345_merged.tif",
307
+ "chip_104_104_merged.tif",
308
+ "chip_109_421_merged.tif"],
309
  inputs=inp,
310
  outputs=[inp1, inp2, inp3, out],
311
  preprocess=preprocess_example,
312
  fn=func,
313
  cache_examples=True)
314
+ with gr.Column():
315
+ gr.Markdown(value='### Model prediction legend')
316
+ gr.Image(value='Legend.png', image_mode='RGB', show_label=False)
317
+
318
 
319
+ demo.launch()
320
 
321
  if __name__ == "__main__":
322
  run_gradio_interface()