Guillermo Uribe Vicencio commited on
Commit
9ec4c35
·
1 Parent(s): d5ab3cb
Files changed (5) hide show
  1. Dockerfile +62 -0
  2. Legend.png +0 -0
  3. README.md +5 -7
  4. app.py +266 -0
  5. requirements.txt +3 -0
Dockerfile ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.8
2
+
3
+
4
+ RUN apt-get update && apt-get install --no-install-recommends -y \
5
+ build-essential \
6
+ # python3.8 \
7
+ # python3-pip \
8
+ # python3-setuptools \
9
+ git \
10
+ wget \
11
+ && apt-get clean && rm -rf /var/lib/apt/lists/*
12
+
13
+ RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y
14
+
15
+ WORKDIR /code
16
+
17
+ RUN useradd -m -u 1000 user
18
+
19
+ # Switch to the "user" user
20
+ USER user
21
+ # Set home to the user's home directory
22
+ ENV HOME=/home/user \
23
+ PATH=/home/user/.local/bin:$PATH \
24
+ PYTHONPATH=$HOME/app \
25
+ PYTHONUNBUFFERED=1 \
26
+ GRADIO_ALLOW_FLAGGING=never \
27
+ GRADIO_NUM_PORTS=1 \
28
+ GRADIO_SERVER_NAME=0.0.0.0 \
29
+ GRADIO_THEME=huggingface \
30
+ SYSTEM=spaces
31
+
32
+ # RUN conda install python=3.8
33
+
34
+ RUN pip install setuptools-rust
35
+ RUN pip install torch==1.11.0+cu115 torchvision==0.12.0+cu115 --extra-index-url https://download.pytorch.org/whl/cu115
36
+ RUN pip install gradio scikit-image pillow openmim
37
+ RUN pip install --upgrade setuptools
38
+
39
+ WORKDIR /home/user
40
+
41
+ RUN --mount=type=secret,id=git_token,mode=0444,required=true \
42
+ git clone --branch mmseg-only https://$(cat /run/secrets/git_token)@github.com/NASA-IMPACT/hls-foundation-os.git
43
+
44
+
45
+ WORKDIR hls-foundation-os
46
+
47
+ RUN git checkout 9968269915db8402bf4a6d0549df9df57d489e5a
48
+
49
+ RUN pip install -e .
50
+
51
+ RUN mim install mmcv-full==1.6.2 -f https://download.openmmlab.com/mmcv/dist/11.5/1.11.0/index.html
52
+
53
+ # Set the working directory to the user's home directory
54
+ WORKDIR $HOME/app
55
+
56
+ # ENV LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/code/miniconda/lib"
57
+
58
+ # Copy the current directory contents into the container at $HOME/app setting the owner to the user
59
+
60
+ COPY --chown=user . $HOME/app
61
+
62
+ CMD ["python3", "app.py"]
Legend.png ADDED
README.md CHANGED
@@ -1,11 +1,9 @@
1
  ---
2
- title: Space Tester
3
- emoji: 👀
4
- colorFrom: pink
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 3.47.1
8
- app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
  ---
 
1
  ---
2
+ title: Prithvi 100M Multi Temporal Crop Classification Demo
3
+ emoji: 📚
4
+ colorFrom: purple
5
+ colorTo: red
6
+ sdk: docker
 
 
7
  pinned: false
8
  license: apache-2.0
9
  ---
app.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ######### pull files
2
+ import os
3
+ from huggingface_hub import hf_hub_download
4
+ config_path=hf_hub_download(repo_id="ibm-nasa-geospatial/Prithvi-100M-multi-temporal-crop-classification",
5
+ filename="multi_temporal_crop_classification_Prithvi_100M.py",
6
+ token=os.environ.get("token"))
7
+ ckpt=hf_hub_download(repo_id="ibm-nasa-geospatial/Prithvi-100M-multi-temporal-crop-classification",
8
+ filename='multi_temporal_crop_classification_Prithvi_100M.pth',
9
+ token=os.environ.get("token"))
10
+ ##########
11
+ import argparse
12
+ from mmcv import Config
13
+
14
+ from mmseg.models import build_segmentor
15
+
16
+ from mmseg.datasets.pipelines import Compose, LoadImageFromFile
17
+
18
+ import rasterio
19
+ import torch
20
+
21
+ from mmseg.apis import init_segmentor
22
+
23
+ from mmcv.parallel import collate, scatter
24
+
25
+ import numpy as np
26
+ import glob
27
+ import os
28
+
29
+ import time
30
+
31
+ import numpy as np
32
+ import gradio as gr
33
+ from functools import partial
34
+
35
+ import pdb
36
+
37
+ import matplotlib.pyplot as plt
38
+
39
+ from skimage import exposure
40
+
41
+ cdl_color_map = [{'value': 1, 'label': 'Natural vegetation', 'rgb': (233,255,190)},
42
+ {'value': 2, 'label': 'Forest', 'rgb': (149,206,147)},
43
+ {'value': 3, 'label': 'Corn', 'rgb': (255,212,0)},
44
+ {'value': 4, 'label': 'Soybeans', 'rgb': (38,115,0)},
45
+ {'value': 5, 'label': 'Wetlands', 'rgb': (128,179,179)},
46
+ {'value': 6, 'label': 'Developed/Barren', 'rgb': (156,156,156)},
47
+ {'value': 7, 'label': 'Open Water', 'rgb': (77,112,163)},
48
+ {'value': 8, 'label': 'Winter Wheat', 'rgb': (168,112,0)},
49
+ {'value': 9, 'label': 'Alfalfa', 'rgb': (255,168,227)},
50
+ {'value': 10, 'label': 'Fallow/Idle cropland', 'rgb': (191,191,122)},
51
+ {'value': 11, 'label': 'Cotton', 'rgb':(255,38,38)},
52
+ {'value': 12, 'label': 'Sorghum', 'rgb':(255,158,15)},
53
+ {'value': 13, 'label': 'Other', 'rgb':(0,175,77)}]
54
+
55
+
56
+ def apply_color_map(rgb, color_map=cdl_color_map):
57
+
58
+
59
+ rgb_mapped = rgb.copy()
60
+
61
+ for map_tmp in cdl_color_map:
62
+
63
+ for i in range(3):
64
+ 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])
65
+
66
+ return rgb_mapped
67
+
68
+
69
+ def stretch_rgb(rgb):
70
+
71
+ ls_pct=0
72
+ pLow, pHigh = np.percentile(rgb[~np.isnan(rgb)], (ls_pct,100-ls_pct))
73
+ img_rescale = exposure.rescale_intensity(rgb, in_range=(pLow,pHigh))
74
+
75
+ return img_rescale
76
+
77
+ def open_tiff(fname):
78
+
79
+ with rasterio.open(fname, "r") as src:
80
+
81
+ data = src.read()
82
+
83
+ return data
84
+
85
+ def write_tiff(img_wrt, filename, metadata):
86
+
87
+ """
88
+ It writes a raster image to file.
89
+
90
+ :param img_wrt: numpy array containing the data (can be 2D for single band or 3D for multiple bands)
91
+ :param filename: file path to the output file
92
+ :param metadata: metadata to use to write the raster to disk
93
+ :return:
94
+ """
95
+
96
+ with rasterio.open(filename, "w", **metadata) as dest:
97
+
98
+ if len(img_wrt.shape) == 2:
99
+
100
+ img_wrt = img_wrt[None]
101
+
102
+ for i in range(img_wrt.shape[0]):
103
+ dest.write(img_wrt[i, :, :], i + 1)
104
+
105
+ return filename
106
+
107
+
108
+ def get_meta(fname):
109
+
110
+ with rasterio.open(fname, "r") as src:
111
+
112
+ meta = src.meta
113
+
114
+ return meta
115
+
116
+ def preprocess_example(example_list):
117
+
118
+ example_list = [os.path.join(os.path.abspath(''), x) for x in example_list]
119
+
120
+ return example_list
121
+
122
+
123
+ def inference_segmentor(model, imgs, custom_test_pipeline=None):
124
+ """Inference image(s) with the segmentor.
125
+
126
+ Args:
127
+ model (nn.Module): The loaded segmentor.
128
+ imgs (str/ndarray or list[str/ndarray]): Either image files or loaded
129
+ images.
130
+
131
+ Returns:
132
+ (list[Tensor]): The segmentation result.
133
+ """
134
+ cfg = model.cfg
135
+ device = next(model.parameters()).device # model device
136
+ # build the data pipeline
137
+ test_pipeline = [LoadImageFromFile()] + cfg.data.test.pipeline[1:] if custom_test_pipeline == None else custom_test_pipeline
138
+ test_pipeline = Compose(test_pipeline)
139
+ # prepare data
140
+ data = []
141
+ imgs = imgs if isinstance(imgs, list) else [imgs]
142
+ for img in imgs:
143
+ img_data = {'img_info': {'filename': img}}
144
+ img_data = test_pipeline(img_data)
145
+ data.append(img_data)
146
+ # print(data.shape)
147
+
148
+ data = collate(data, samples_per_gpu=len(imgs))
149
+ if next(model.parameters()).is_cuda:
150
+ # data = collate(data, samples_per_gpu=len(imgs))
151
+ # scatter to specified GPU
152
+ data = scatter(data, [device])[0]
153
+ else:
154
+ # img_metas = scatter(data['img_metas'],'cpu')
155
+ # data['img_metas'] = [i.data[0] for i in data['img_metas']]
156
+
157
+ img_metas = data['img_metas'].data[0]
158
+ img = data['img']
159
+ data = {'img': img, 'img_metas':img_metas}
160
+
161
+ with torch.no_grad():
162
+ result = model(return_loss=False, rescale=True, **data)
163
+ return result
164
+
165
+
166
+ def process_rgb(input, mask, indexes):
167
+
168
+
169
+ rgb = stretch_rgb((input[indexes, :, :].transpose((1,2,0))/10000*255).astype(np.uint8))
170
+ rgb = np.where(mask.transpose((1,2,0)) == 1, 0, rgb)
171
+ rgb = np.where(rgb < 0, 0, rgb)
172
+ rgb = np.where(rgb > 255, 255, rgb)
173
+
174
+ return rgb
175
+
176
+ def inference_on_file(target_image, model, custom_test_pipeline):
177
+
178
+ target_image = target_image.name
179
+ time_taken=-1
180
+ st = time.time()
181
+ print('Running inference...')
182
+ try:
183
+ result = inference_segmentor(model, target_image, custom_test_pipeline)
184
+ except:
185
+ print('Error: Try different channels order.')
186
+ model.cfg.data.test.pipeline[0]['channels_last'] = True
187
+ result = inference_segmentor(model, target_image, custom_test_pipeline)
188
+ print("Output has shape: " + str(result[0].shape))
189
+
190
+ ##### get metadata mask
191
+ input = open_tiff(target_image)
192
+ meta = get_meta(target_image)
193
+ mask = np.where(input == meta['nodata'], 1, 0)
194
+ mask = np.max(mask, axis=0)[None]
195
+
196
+ rgb1 = process_rgb(input, mask, [2, 1, 0])
197
+ rgb2 = process_rgb(input, mask, [8, 7, 6])
198
+ rgb3 = process_rgb(input, mask, [14, 13, 12])
199
+
200
+ result[0] = np.where(mask == 1, 0, result[0])
201
+
202
+ et = time.time()
203
+ time_taken = np.round(et - st, 1)
204
+ print(f'Inference completed in {str(time_taken)} seconds')
205
+
206
+ output=result[0][0] + 1
207
+ output = np.vstack([output[None], output[None], output[None]]).astype(np.uint8)
208
+ output=apply_color_map(output).transpose((1,2,0))
209
+
210
+ return rgb1,rgb2,rgb3,output
211
+
212
+ def process_test_pipeline(custom_test_pipeline, bands=None):
213
+
214
+ # change extracted bands if necessary
215
+ if bands is not None:
216
+
217
+ extract_index = [i for i, x in enumerate(custom_test_pipeline) if x['type'] == 'BandsExtract' ]
218
+
219
+ if len(extract_index) > 0:
220
+
221
+ custom_test_pipeline[extract_index[0]]['bands'] = eval(bands)
222
+
223
+ collect_index = [i for i, x in enumerate(custom_test_pipeline) if x['type'].find('Collect') > -1]
224
+
225
+ # adapt collected keys if necessary
226
+ if len(collect_index) > 0:
227
+
228
+ keys = ['img_info', 'filename', 'ori_filename', 'img', 'img_shape', 'ori_shape', 'pad_shape', 'scale_factor', 'img_norm_cfg']
229
+ custom_test_pipeline[collect_index[0]]['meta_keys'] = keys
230
+
231
+ return custom_test_pipeline
232
+
233
+ config = Config.fromfile(config_path)
234
+ config.model.backbone.pretrained=None
235
+ model = init_segmentor(config, ckpt, device='cpu')
236
+ custom_test_pipeline=process_test_pipeline(model.cfg.data.test.pipeline, None)
237
+
238
+ func = partial(inference_on_file, model=model, custom_test_pipeline=custom_test_pipeline)
239
+
240
+ with gr.Blocks() as demo:
241
+
242
+ gr.Markdown(value='# Prithvi multi temporal crop classification')
243
+ 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
244
+ 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.
245
+ ''')
246
+ with gr.Row():
247
+ with gr.Column():
248
+ inp = gr.File()
249
+ btn = gr.Button("Submit")
250
+
251
+ with gr.Row():
252
+ inp1=gr.Image(image_mode='RGB', scale=10, label='T1')
253
+ inp2=gr.Image(image_mode='RGB', scale=10, label='T2')
254
+ inp3=gr.Image(image_mode='RGB', scale=10, label='T3')
255
+ out = gr.Image(image_mode='RGB', scale=10, label='Model prediction')
256
+ # gr.Image(value='Legend.png', image_mode='RGB', scale=2, show_label=False)
257
+
258
+ btn.click(fn=func, inputs=inp, outputs=[inp1, inp2, inp3, out])
259
+
260
+ with gr.Row():
261
+ with gr.Column():
262
+ gr.Markdown(value='### Model prediction legend')
263
+ gr.Image(value='Legend.png', image_mode='RGB', show_label=False)
264
+
265
+
266
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ pytorch==1.7.1
2
+ torchvision==0.8.2
3
+ openmim