Commit
·
5af1287
1
Parent(s):
b2fefdb
add files
Browse files- .gitattributes +3 -0
- Bolivia_432776_S2Hand.tif +3 -0
- Dockerfile +78 -0
- Spain_7370579_S2Hand.tif +3 -0
- USA_430764_S2Hand.tif +3 -0
- app.py +223 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
Bolivia_432776_S2Hand.tif filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
Spain_7370579_S2Hand.tif filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
USA_430764_S2Hand.tif filter=lfs diff=lfs merge=lfs -text
|
Bolivia_432776_S2Hand.tif
ADDED
|
|
Git LFS Details
|
Dockerfile
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ubuntu:18.04
|
| 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 |
+
# add conda
|
| 18 |
+
RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -P /code/
|
| 19 |
+
RUN chmod 777 /code/Miniconda3-latest-Linux-x86_64.sh
|
| 20 |
+
RUN /code/Miniconda3-latest-Linux-x86_64.sh -b -p /code/miniconda
|
| 21 |
+
ENV PATH="/code/miniconda/bin:${PATH}"
|
| 22 |
+
|
| 23 |
+
RUN groupadd miniconda
|
| 24 |
+
RUN chgrp -R miniconda /code/miniconda/
|
| 25 |
+
RUN chmod 770 -R /code/miniconda/
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# Set up a new user named "user" with user ID 1000
|
| 29 |
+
RUN useradd -m -u 1000 user
|
| 30 |
+
RUN adduser user miniconda
|
| 31 |
+
|
| 32 |
+
# Switch to the "user" user
|
| 33 |
+
USER user
|
| 34 |
+
# Set home to the user's home directory
|
| 35 |
+
ENV HOME=/home/user \
|
| 36 |
+
PATH=/home/user/.local/bin:$PATH \
|
| 37 |
+
PYTHONPATH=$HOME/app \
|
| 38 |
+
PYTHONUNBUFFERED=1 \
|
| 39 |
+
GRADIO_ALLOW_FLAGGING=never \
|
| 40 |
+
GRADIO_NUM_PORTS=1 \
|
| 41 |
+
GRADIO_SERVER_NAME=0.0.0.0 \
|
| 42 |
+
GRADIO_THEME=huggingface \
|
| 43 |
+
SYSTEM=spaces
|
| 44 |
+
|
| 45 |
+
RUN conda install python=3.8
|
| 46 |
+
|
| 47 |
+
RUN pip3 install setuptools-rust
|
| 48 |
+
|
| 49 |
+
RUN conda install pillow -y
|
| 50 |
+
|
| 51 |
+
RUN pip3 install torch==1.11.0+cu115 torchvision==0.12.0+cu115 --extra-index-url https://download.pytorch.org/whl/cu115
|
| 52 |
+
|
| 53 |
+
RUN pip3 install openmim
|
| 54 |
+
|
| 55 |
+
RUN conda install -c conda-forge gradio -y
|
| 56 |
+
|
| 57 |
+
WORKDIR /home/user
|
| 58 |
+
|
| 59 |
+
RUN --mount=type=secret,id=git_token,mode=0444,required=true \
|
| 60 |
+
git clone --branch mmseg-only https://$(cat /run/secrets/git_token)@github.com/NASA-IMPACT/hls-foundation-os.git
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
WORKDIR hls-foundation-os
|
| 64 |
+
|
| 65 |
+
RUN pip3 install -e .
|
| 66 |
+
|
| 67 |
+
RUN mim install mmcv-full==1.6.2 -f https://download.openmmlab.com/mmcv/dist/11.5/1.11.0/index.html
|
| 68 |
+
|
| 69 |
+
RUN pip3 install rasterio scikit-image
|
| 70 |
+
# Set the working directory to the user's home directory
|
| 71 |
+
WORKDIR $HOME/app
|
| 72 |
+
|
| 73 |
+
ENV LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/code/miniconda/lib"
|
| 74 |
+
|
| 75 |
+
# Copy the current directory contents into the container at $HOME/app setting the owner to the user
|
| 76 |
+
COPY --chown=user . $HOME/app
|
| 77 |
+
|
| 78 |
+
CMD ["python3", "app.py"]
|
Spain_7370579_S2Hand.tif
ADDED
|
|
Git LFS Details
|
USA_430764_S2Hand.tif
ADDED
|
|
Git LFS Details
|
app.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-sen1floods11", filename="sen1floods11_Prithvi_100M.py", token=os.environ.get("token"))
|
| 5 |
+
ckpt=hf_hub_download(repo_id="ibm-nasa-geospatial/Prithvi-100M-sen1floods11", filename='sen1floods11_Prithvi_100M.pth', token=os.environ.get("token"))
|
| 6 |
+
##########
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
from mmcv import Config
|
| 11 |
+
|
| 12 |
+
from mmseg.models import build_segmentor
|
| 13 |
+
|
| 14 |
+
from mmseg.datasets.pipelines import Compose, LoadImageFromFile
|
| 15 |
+
|
| 16 |
+
import rasterio
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
from mmseg.apis import init_segmentor
|
| 20 |
+
|
| 21 |
+
from mmcv.parallel import collate, scatter
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import glob
|
| 25 |
+
import os
|
| 26 |
+
|
| 27 |
+
import time
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import gradio as gr
|
| 31 |
+
from functools import partial
|
| 32 |
+
|
| 33 |
+
import pdb
|
| 34 |
+
|
| 35 |
+
import matplotlib.pyplot as plt
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def open_tiff(fname):
|
| 39 |
+
|
| 40 |
+
with rasterio.open(fname, "r") as src:
|
| 41 |
+
|
| 42 |
+
data = src.read()
|
| 43 |
+
|
| 44 |
+
return data
|
| 45 |
+
|
| 46 |
+
def write_tiff(img_wrt, filename, metadata):
|
| 47 |
+
|
| 48 |
+
"""
|
| 49 |
+
It writes a raster image to file.
|
| 50 |
+
|
| 51 |
+
:param img_wrt: numpy array containing the data (can be 2D for single band or 3D for multiple bands)
|
| 52 |
+
:param filename: file path to the output file
|
| 53 |
+
:param metadata: metadata to use to write the raster to disk
|
| 54 |
+
:return:
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
with rasterio.open(filename, "w", **metadata) as dest:
|
| 58 |
+
|
| 59 |
+
if len(img_wrt.shape) == 2:
|
| 60 |
+
|
| 61 |
+
img_wrt = img_wrt[None]
|
| 62 |
+
|
| 63 |
+
for i in range(img_wrt.shape[0]):
|
| 64 |
+
dest.write(img_wrt[i, :, :], i + 1)
|
| 65 |
+
|
| 66 |
+
return filename
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def get_meta(fname):
|
| 70 |
+
|
| 71 |
+
with rasterio.open(fname, "r") as src:
|
| 72 |
+
|
| 73 |
+
meta = src.meta
|
| 74 |
+
|
| 75 |
+
return meta
|
| 76 |
+
|
| 77 |
+
def preprocess_example(example_list):
|
| 78 |
+
|
| 79 |
+
example_list = [os.path.join(os.path.abspath(''), x) for x in example_list]
|
| 80 |
+
|
| 81 |
+
return example_list
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def inference_segmentor(model, imgs, custom_test_pipeline=None):
|
| 85 |
+
"""Inference image(s) with the segmentor.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
model (nn.Module): The loaded segmentor.
|
| 89 |
+
imgs (str/ndarray or list[str/ndarray]): Either image files or loaded
|
| 90 |
+
images.
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
(list[Tensor]): The segmentation result.
|
| 94 |
+
"""
|
| 95 |
+
cfg = model.cfg
|
| 96 |
+
device = next(model.parameters()).device # model device
|
| 97 |
+
# build the data pipeline
|
| 98 |
+
test_pipeline = [LoadImageFromFile()] + cfg.data.test.pipeline[1:] if custom_test_pipeline == None else custom_test_pipeline
|
| 99 |
+
test_pipeline = Compose(test_pipeline)
|
| 100 |
+
# prepare data
|
| 101 |
+
data = []
|
| 102 |
+
imgs = imgs if isinstance(imgs, list) else [imgs]
|
| 103 |
+
for img in imgs:
|
| 104 |
+
img_data = {'img_info': {'filename': img}}
|
| 105 |
+
img_data = test_pipeline(img_data)
|
| 106 |
+
data.append(img_data)
|
| 107 |
+
# print(data.shape)
|
| 108 |
+
|
| 109 |
+
data = collate(data, samples_per_gpu=len(imgs))
|
| 110 |
+
if next(model.parameters()).is_cuda:
|
| 111 |
+
# data = collate(data, samples_per_gpu=len(imgs))
|
| 112 |
+
# scatter to specified GPU
|
| 113 |
+
data = scatter(data, [device])[0]
|
| 114 |
+
else:
|
| 115 |
+
# img_metas = scatter(data['img_metas'],'cpu')
|
| 116 |
+
# data['img_metas'] = [i.data[0] for i in data['img_metas']]
|
| 117 |
+
|
| 118 |
+
img_metas = data['img_metas'].data[0]
|
| 119 |
+
img = data['img']
|
| 120 |
+
data = {'img': img, 'img_metas':img_metas}
|
| 121 |
+
|
| 122 |
+
with torch.no_grad():
|
| 123 |
+
result = model(return_loss=False, rescale=True, **data)
|
| 124 |
+
return result
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def inference_on_file(target_image, model, custom_test_pipeline):
|
| 128 |
+
|
| 129 |
+
target_image = target_image.name
|
| 130 |
+
# print(type(target_image))
|
| 131 |
+
|
| 132 |
+
# output_image = target_image.replace('.tif', '_pred.tif')
|
| 133 |
+
time_taken=-1
|
| 134 |
+
|
| 135 |
+
st = time.time()
|
| 136 |
+
print('Running inference...')
|
| 137 |
+
result = inference_segmentor(model, target_image, custom_test_pipeline)
|
| 138 |
+
print("Output has shape: " + str(result[0].shape))
|
| 139 |
+
|
| 140 |
+
##### get metadata mask
|
| 141 |
+
mask = open_tiff(target_image)
|
| 142 |
+
# rgb = mask[[2, 1, 0], :, :].transpose((1,2,0))
|
| 143 |
+
rgb = mask[[5, 3, 2], :, :].transpose((1,2,0))
|
| 144 |
+
meta = get_meta(target_image)
|
| 145 |
+
mask = np.where(mask == meta['nodata'], 1, 0)
|
| 146 |
+
mask = np.max(mask, axis=0)[None]
|
| 147 |
+
|
| 148 |
+
result[0] = np.where(mask == 1, -1, result[0])
|
| 149 |
+
|
| 150 |
+
##### Save file to disk
|
| 151 |
+
meta["count"] = 1
|
| 152 |
+
meta["dtype"] = "int16"
|
| 153 |
+
meta["compress"] = "lzw"
|
| 154 |
+
meta["nodata"] = -1
|
| 155 |
+
print('Saving output...')
|
| 156 |
+
# write_tiff(result[0], output_image, meta)
|
| 157 |
+
et = time.time()
|
| 158 |
+
time_taken = np.round(et - st, 1)
|
| 159 |
+
print(f'Inference completed in {str(time_taken)} seconds')
|
| 160 |
+
|
| 161 |
+
return rgb, result[0][0]*255
|
| 162 |
+
|
| 163 |
+
def process_test_pipeline(custom_test_pipeline, bands=None):
|
| 164 |
+
|
| 165 |
+
# change extracted bands if necessary
|
| 166 |
+
if bands is not None:
|
| 167 |
+
|
| 168 |
+
extract_index = [i for i, x in enumerate(custom_test_pipeline) if x['type'] == 'BandsExtract' ]
|
| 169 |
+
|
| 170 |
+
if len(extract_index) > 0:
|
| 171 |
+
|
| 172 |
+
custom_test_pipeline[extract_index[0]]['bands'] = eval(bands)
|
| 173 |
+
|
| 174 |
+
collect_index = [i for i, x in enumerate(custom_test_pipeline) if x['type'].find('Collect') > -1]
|
| 175 |
+
|
| 176 |
+
# adapt collected keys if necessary
|
| 177 |
+
if len(collect_index) > 0:
|
| 178 |
+
|
| 179 |
+
keys = ['img_info', 'filename', 'ori_filename', 'img', 'img_shape', 'ori_shape', 'pad_shape', 'scale_factor', 'img_norm_cfg']
|
| 180 |
+
custom_test_pipeline[collect_index[0]]['meta_keys'] = keys
|
| 181 |
+
|
| 182 |
+
return custom_test_pipeline
|
| 183 |
+
|
| 184 |
+
config = Config.fromfile(config_path)
|
| 185 |
+
config.model.backbone.pretrained=None
|
| 186 |
+
model = init_segmentor(config, ckpt, device='cpu')
|
| 187 |
+
custom_test_pipeline=process_test_pipeline(model.cfg.data.test.pipeline, None)
|
| 188 |
+
|
| 189 |
+
func = partial(inference_on_file, model=model, custom_test_pipeline=custom_test_pipeline)
|
| 190 |
+
|
| 191 |
+
with gr.Blocks() as demo:
|
| 192 |
+
|
| 193 |
+
gr.Markdown(value='# Prithvi burn scars detection')
|
| 194 |
+
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 detect water at a higher resolution than it was trained on (i.e. 10m versus 30m) using Sentinel 2 imagery from on the [sen1floods11 dataset](https://github.com/cloudtostreet/Sen1Floods11). More detailes can be found [here](https://huggingface.co/ibm-nasa-geospatial/Prithvi-100M-sen1floods11).\n
|
| 195 |
+
The user needs to provide an HLS geotiff image, including the following channels in reflectance units multiplied by 10,000 (e.g. to save on space): Blue, Green, Red, Narrow NIR, SWIR, SWIR 2.
|
| 196 |
+
''')
|
| 197 |
+
with gr.Row():
|
| 198 |
+
with gr.Column():
|
| 199 |
+
inp = gr.File()
|
| 200 |
+
btn = gr.Button("Submit")
|
| 201 |
+
|
| 202 |
+
with gr.Row():
|
| 203 |
+
gr.Markdown(value='### Input RGB')
|
| 204 |
+
gr.Markdown(value='### Model prediction (Black: Land; White: Water)')
|
| 205 |
+
|
| 206 |
+
with gr.Row():
|
| 207 |
+
out1=gr.Image(image_mode='RGB')
|
| 208 |
+
out2 = gr.Image(image_mode='L')
|
| 209 |
+
|
| 210 |
+
btn.click(fn=func, inputs=inp, outputs=[out1, out2])
|
| 211 |
+
|
| 212 |
+
with gr.Row():
|
| 213 |
+
gr.Examples(examples=["subsetted_512x512_HLS.S30.T10TGS.2020245.v1.4_merged.tif",
|
| 214 |
+
"subsetted_512x512_HLS.S30.T10TGS.2018285.v1.4_merged.tif",
|
| 215 |
+
"subsetted_512x512_HLS.S30.T10UGV.2020218.v1.4_merged.tif"],
|
| 216 |
+
inputs=inp,
|
| 217 |
+
outputs=[out1, out2],
|
| 218 |
+
preprocess=preprocess_example,
|
| 219 |
+
fn=func,
|
| 220 |
+
cache_examples=True,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
demo.launch()
|