Spaces:
Sleeping
Sleeping
Stefan Scholz commited on
Commit ·
b3d5f8e
1
Parent(s): dccb1c9
fix error with reloading app
Browse files
app.py
CHANGED
|
@@ -7,345 +7,348 @@ Application for demo space
|
|
| 7 |
|
| 8 |
"""
|
| 9 |
|
| 10 |
-
import os
|
| 11 |
-
import sys
|
| 12 |
-
import torch
|
| 13 |
-
import requests
|
| 14 |
-
import numpy as np
|
| 15 |
-
import pandas as pd
|
| 16 |
import gradio as gr
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
"""
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
"""
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
predictions = self.predictor(image)
|
| 163 |
-
|
| 164 |
-
return predictions
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
def get_clip_embeddings(vocabulary, prompt='a '):
|
| 168 |
-
text_encoder = build_text_encoder(pretrain=True)
|
| 169 |
-
text_encoder.eval()
|
| 170 |
-
texts = [prompt + x for x in vocabulary]
|
| 171 |
-
emb = text_encoder(texts).detach().permute(1, 0).contiguous().cpu()
|
| 172 |
-
return emb
|
| 173 |
-
|
| 174 |
-
# download model weights
|
| 175 |
-
model_path = "models/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth"
|
| 176 |
-
model_url = "https://dl.fbaipublicfiles.com/detic/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth"
|
| 177 |
-
|
| 178 |
-
if not os.path.exists(model_path):
|
| 179 |
-
print("Download model weights")
|
| 180 |
-
r = requests.get(model_url)
|
| 181 |
-
with open(model_path, "wb") as f:
|
| 182 |
-
f.write(r.content)
|
| 183 |
-
|
| 184 |
-
# config
|
| 185 |
-
cfg_lvis = get_cfg() # weight-file
|
| 186 |
-
add_centernet_config(cfg_lvis)
|
| 187 |
-
add_detic_config(cfg_lvis)
|
| 188 |
-
cfg_lvis.merge_from_file("modules/Detic/configs/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.yaml")
|
| 189 |
-
cfg_lvis.MODEL.WEIGHTS = "models/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth"
|
| 190 |
-
cfg_lvis.MODEL.ROI_BOX_HEAD.CAT_FREQ_PATH = "modules/Detic/datasets/metadata/lvis_v1_train_cat_info.json"
|
| 191 |
-
cfg_lvis.MODEL.ROI_BOX_HEAD.ZEROSHOT_WEIGHT_PATH = "rand" # load later
|
| 192 |
-
cfg_lvis.MODEL.ROI_HEADS.ONE_CLASS_PER_PROPOSAL = True
|
| 193 |
-
cfg_lvis.freeze()
|
| 194 |
-
# predictor
|
| 195 |
-
predictor_lvis = LVISPredictor(cfg_lvis, vocab="lvis")
|
| 196 |
-
|
| 197 |
-
else:
|
| 198 |
-
# get coco model
|
| 199 |
-
print("Get model for vocabulary COCO")
|
| 200 |
-
|
| 201 |
-
# config
|
| 202 |
-
cfg_coco = get_cfg()
|
| 203 |
-
# device
|
| 204 |
-
cfg_coco.MODEL.DEVICE = "cpu"
|
| 205 |
-
# add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
|
| 206 |
-
cfg_coco.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml"))
|
| 207 |
-
cfg_coco.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.1 # set threshold for this model
|
| 208 |
-
# Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
|
| 209 |
-
cfg_coco.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml")
|
| 210 |
-
|
| 211 |
-
# predictor
|
| 212 |
-
predictor_coco = DefaultPredictor(cfg_coco)
|
| 213 |
-
|
| 214 |
-
# get coco model
|
| 215 |
-
print("Get model for vocabulary LVIS")
|
| 216 |
-
|
| 217 |
-
# config
|
| 218 |
-
cfg_lvis = get_cfg()
|
| 219 |
-
# device
|
| 220 |
-
cfg_lvis.MODEL.DEVICE = "cpu"
|
| 221 |
-
# add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
|
| 222 |
-
cfg_lvis.merge_from_file(model_zoo.get_config_file("LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml"))
|
| 223 |
-
cfg_lvis.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.1 # set threshold for this model
|
| 224 |
-
# Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
|
| 225 |
-
cfg_lvis.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml")
|
| 226 |
-
|
| 227 |
-
# predictor
|
| 228 |
-
predictor_lvis = DefaultPredictor(cfg_lvis)
|
| 229 |
-
|
| 230 |
-
return predictor_coco, cfg_coco, predictor_lvis, cfg_lvis
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
def predict(image, vocabulary, feature_aggregation):
|
| 234 |
-
"""
|
| 235 |
-
Predict segmented image and feature vector
|
| 236 |
-
|
| 237 |
-
:param image:
|
| 238 |
-
:param vocabulary:
|
| 239 |
-
:param feature_aggregation:
|
| 240 |
-
:return:
|
| 241 |
-
"""
|
| 242 |
-
|
| 243 |
-
# convert image and resize if necessary
|
| 244 |
-
image = image.convert('RGB')
|
| 245 |
-
image.thumbnail((2000, 2000), Image.LANCZOS)
|
| 246 |
-
image = np.array(image)
|
| 247 |
-
|
| 248 |
-
# check vocabulary
|
| 249 |
-
if vocabulary == "COCO":
|
| 250 |
-
# get predictions
|
| 251 |
-
predictions = predictor_coco(image)
|
| 252 |
-
|
| 253 |
-
# visualize predictions
|
| 254 |
-
visualizer = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg_coco.DATASETS.TRAIN[0]), instance_mode=ColorMode.SEGMENTATION)
|
| 255 |
-
image_segmented = visualizer.draw_instance_predictions(predictions["instances"].to("cpu"))
|
| 256 |
-
image_segmented = Image.fromarray(image_segmented.get_image()[:, :, ::-1])
|
| 257 |
-
|
| 258 |
-
# get class names
|
| 259 |
-
class_names = {class_num: class_name.lower() for class_num, class_name in enumerate(MetadataCatalog.get(cfg_coco.DATASETS.TRAIN[0]).thing_classes)}
|
| 260 |
-
|
| 261 |
-
elif vocabulary == "LVIS":
|
| 262 |
-
# get predictions
|
| 263 |
-
predictions = predictor_lvis(image)
|
| 264 |
-
|
| 265 |
-
# visualize predictions
|
| 266 |
-
visualizer = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg_lvis.DATASETS.TRAIN[0]), instance_mode=ColorMode.SEGMENTATION)
|
| 267 |
-
image_segmented = visualizer.draw_instance_predictions(predictions["instances"].to("cpu"))
|
| 268 |
-
image_segmented = Image.fromarray(image_segmented.get_image()[:, :, ::-1])
|
| 269 |
-
|
| 270 |
-
# get class names
|
| 271 |
-
class_names = {class_num: class_name.lower() for class_num, class_name in enumerate(MetadataCatalog.get(cfg_lvis.DATASETS.TRAIN[0]).thing_classes)}
|
| 272 |
-
|
| 273 |
-
else:
|
| 274 |
-
raise Exception("Unknown vocabulary")
|
| 275 |
-
|
| 276 |
-
# prepare segments in long format
|
| 277 |
-
segments_long_df = pd.DataFrame([])
|
| 278 |
-
|
| 279 |
-
for seg_num, seg_score, seg_mask in zip(predictions["instances"].pred_classes, predictions["instances"].scores, predictions["instances"].pred_masks):
|
| 280 |
-
segments_long_df = pd.concat([segments_long_df, pd.Series({
|
| 281 |
-
"id": "image_1",
|
| 282 |
-
"seg_num": seg_num.item(),
|
| 283 |
-
"seg_name": class_names[seg_num.item()],
|
| 284 |
-
"seg_score": seg_score.item(),
|
| 285 |
-
"seg_prop": (torch.sum(seg_mask == True) / torch.numel(seg_mask)).item()
|
| 286 |
-
}).to_frame().T], ignore_index=True)
|
| 287 |
-
|
| 288 |
-
# TODO: delete segments with less than 0.1
|
| 289 |
-
#segments_long_df = segments_long_df.loc[(segments_long_df["seg_score"] >= 0.1)].reset_index(drop=True)
|
| 290 |
-
|
| 291 |
-
if feature_aggregation == "bin":
|
| 292 |
-
# get segments wide
|
| 293 |
-
segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_score"], aggfunc={"seg_score": ["any"]})
|
| 294 |
-
cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
|
| 295 |
-
cols_missing = [f'{vocabulary.lower()}_{category.lower()}_bin' for category in cols_missing]
|
| 296 |
-
segments_wide_df.columns = [f'{vocabulary.lower()}_{label.lower()}_bin' for var, agg, label in segments_wide_df.columns]
|
| 297 |
-
segments_wide_df = segments_wide_df.reset_index()
|
| 298 |
-
segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
|
| 299 |
-
segments_wide_df = segments_wide_df.fillna(0)
|
| 300 |
-
# get cols
|
| 301 |
-
cols = [f'{vocabulary.lower()}_{cat.lower()}_bin' for cat in class_names.values()]
|
| 302 |
-
# get vector
|
| 303 |
-
feature_vector = segments_wide_df.loc[:, cols].astype(int).to_json(orient="records")
|
| 304 |
-
|
| 305 |
-
elif feature_aggregation == "count":
|
| 306 |
-
segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_score"], aggfunc={"seg_score": ["count"]})
|
| 307 |
-
cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
|
| 308 |
-
cols_missing = [f'{vocabulary.lower()}_{category.lower()}_count' for category in cols_missing]
|
| 309 |
-
segments_wide_df.columns = [f'{vocabulary.lower()}_{label.lower()}_count' for var, agg, label in segments_wide_df.columns]
|
| 310 |
-
segments_wide_df = segments_wide_df.reset_index()
|
| 311 |
-
segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
|
| 312 |
-
segments_wide_df = segments_wide_df.fillna(0)
|
| 313 |
-
# get cols
|
| 314 |
-
cols = [f'{vocabulary.lower()}_{cat.lower()}_count' for cat in class_names.values()]
|
| 315 |
-
# get vector
|
| 316 |
-
feature_vector = segments_wide_df.loc[:, cols].astype(int).to_json(orient="records")
|
| 317 |
-
|
| 318 |
-
elif feature_aggregation == "area_max":
|
| 319 |
-
segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_prop"], aggfunc={"seg_prop": ["max"]})
|
| 320 |
-
cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
|
| 321 |
-
cols_missing = [f"{vocabulary.lower()}_{category.lower()}_area_max" for category in cols_missing]
|
| 322 |
-
segments_wide_df.columns = [f"{vocabulary.lower()}_{label.lower()}_area_max" for var, agg, label in segments_wide_df.columns]
|
| 323 |
-
segments_wide_df = segments_wide_df.reset_index()
|
| 324 |
-
segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
|
| 325 |
-
segments_wide_df = segments_wide_df.fillna(0)
|
| 326 |
-
# get cols
|
| 327 |
-
cols = [f"{vocabulary.lower()}_{cat.lower()}_area_max" for cat in class_names.values()]
|
| 328 |
-
# get vector
|
| 329 |
-
feature_vector = segments_wide_df.loc[:, cols].astype(float).to_json(orient="records")
|
| 330 |
-
|
| 331 |
-
elif feature_aggregation == "area_sum":
|
| 332 |
-
segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_prop"], aggfunc={"seg_prop": ["sum"]})
|
| 333 |
-
cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
|
| 334 |
-
cols_missing = [f"{vocabulary.lower()}_{category.lower()}_area_sum" for category in cols_missing]
|
| 335 |
-
segments_wide_df.columns = [f"{vocabulary.lower()}_{label.lower()}_area_sum" for var, agg, label in segments_wide_df.columns]
|
| 336 |
-
segments_wide_df = segments_wide_df.reset_index()
|
| 337 |
-
segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
|
| 338 |
-
segments_wide_df = segments_wide_df.fillna(0)
|
| 339 |
-
# get cols
|
| 340 |
-
cols = [f"{vocabulary.lower()}_{cat.lower()}_area_sum" for cat in class_names.values()]
|
| 341 |
-
# get vector
|
| 342 |
-
feature_vector = segments_wide_df.loc[:, cols].astype(float).to_json(orient="records")
|
| 343 |
-
|
| 344 |
-
return image_segmented, feature_vector
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
# get models
|
| 348 |
-
predictor_coco, cfg_coco, predictor_lvis, cfg_lvis = get_models()
|
| 349 |
|
| 350 |
# define app interface
|
| 351 |
app = gr.Interface(
|
|
|
|
| 7 |
|
| 8 |
"""
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
import gradio as gr
|
| 11 |
+
|
| 12 |
+
# fix issue with reload error
|
| 13 |
+
if gr.NO_RELOAD:
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import torch
|
| 17 |
+
import requests
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
from PIL import Image
|
| 21 |
+
from detectron2 import model_zoo
|
| 22 |
+
from detectron2.config import get_cfg
|
| 23 |
+
from detectron2.data import MetadataCatalog
|
| 24 |
+
from detectron2.engine import DefaultPredictor
|
| 25 |
+
from detectron2.utils.visualizer import ColorMode, Visualizer
|
| 26 |
+
from detectron2.projects.deeplab import add_deeplab_config, build_lr_scheduler
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_article():
|
| 30 |
+
"""
|
| 31 |
+
Get article
|
| 32 |
+
|
| 33 |
+
:return:
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
if torch.cuda.is_available():
|
| 37 |
+
article = """
|
| 38 |
+
The space demonstrates the method introduced in the paper 'Improving
|
| 39 |
+
Computer Vision Interpretability: Transparent Two-level Classification for
|
| 40 |
+
Complex Scenes'.
|
| 41 |
+
|
| 42 |
+
The segments from the COCO vocabulary are recognized with the
|
| 43 |
+
segmentation model by [Li et al. (2022)](https://arxiv.org/abs/2206.02777),
|
| 44 |
+
while they are recognized from the LVIS vocabulary with the model by
|
| 45 |
+
[Zhou et al (2022)](https://arxiv.org/abs/2201.02605).
|
| 46 |
+
"""
|
| 47 |
+
else:
|
| 48 |
+
article = """
|
| 49 |
+
The space demonstrates the method introduced in the paper 'Improving
|
| 50 |
+
Computer Vision Interpretability: Transparent Two-level Classification for
|
| 51 |
+
Complex Scenes'.
|
| 52 |
+
|
| 53 |
+
⚠️ The segments from the COCO vocabulary as well as the LVIS v0.5 vocabulary
|
| 54 |
+
are recognized with the segmentation model by [Wu et al., 2017](https://github.com/facebookresearch/detectron2/tree/main).
|
| 55 |
+
If you want to use the same segmentation models as in the paper, then you
|
| 56 |
+
have to duplicate this space in a space environment with GPU accelerator.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
return article
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def get_models():
|
| 63 |
"""
|
| 64 |
+
Get article
|
| 65 |
+
|
| 66 |
+
:return:
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
if torch.cuda.is_available():
|
| 70 |
+
# get coco model
|
| 71 |
+
print("Get model for vocabulary COCO")
|
| 72 |
+
|
| 73 |
+
# import modules only available with gpu
|
| 74 |
+
sys.path.insert(0, "./modules/MaskDINO")
|
| 75 |
+
|
| 76 |
+
from maskdino import add_maskformer2_config
|
| 77 |
+
|
| 78 |
+
# download model weights
|
| 79 |
+
model_path = "models/maskdino_swinl_50ep_300q_hid2048_3sd1_instance_maskenhanced_mask52.3ap_box59.0ap.pth"
|
| 80 |
+
model_url = "https://github.com/IDEA-Research/detrex-storage/releases/download/maskdino-v0.1.0/maskdino_swinl_50ep_300q_hid2048_3sd1_instance_maskenhanced_mask52.3ap_box59.0ap.pth"
|
| 81 |
+
|
| 82 |
+
if not os.path.exists(model_path):
|
| 83 |
+
print("Download model weights for vocabulary COCO")
|
| 84 |
+
r = requests.get(model_url)
|
| 85 |
+
with open(model_path, "wb") as f:
|
| 86 |
+
f.write(r.content)
|
| 87 |
+
|
| 88 |
+
# config
|
| 89 |
+
cfg_coco = get_cfg()
|
| 90 |
+
# for poly lr schedule
|
| 91 |
+
add_deeplab_config(cfg_coco)
|
| 92 |
+
add_maskformer2_config(cfg_coco)
|
| 93 |
+
cfg_coco.merge_from_file("modules/MaskDINO/configs/coco/instance-segmentation/swin/maskdino_R50_bs16_50ep_4s_dowsample1_2048.yaml")
|
| 94 |
+
cfg_coco.MODEL.WEIGHTS = "models/maskdino_swinl_50ep_300q_hid2048_3sd1_instance_maskenhanced_mask52.3ap_box59.0ap.pth"
|
| 95 |
+
cfg_coco.MODEL.RETINANET.SCORE_THRESH_TEST = 0.0 # no effect
|
| 96 |
+
cfg_coco.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.0 # no effect
|
| 97 |
+
cfg_coco.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = 0.0 # no effect
|
| 98 |
+
cfg_coco.freeze()
|
| 99 |
+
|
| 100 |
+
# predictor
|
| 101 |
+
predictor_coco = DefaultPredictor(cfg_coco)
|
| 102 |
+
|
| 103 |
+
# get lvis model
|
| 104 |
+
print("Get model for vocabulary LVIS")
|
| 105 |
+
|
| 106 |
+
# import modules only available with gpu
|
| 107 |
+
sys.path.insert(0, "./modules/Detic")
|
| 108 |
+
sys.path.insert(0, "./modules/Detic/third_party/CenterNet2")
|
| 109 |
+
|
| 110 |
+
from centernet.config import add_centernet_config
|
| 111 |
+
from detic.config import add_detic_config
|
| 112 |
+
from detic.modeling.utils import reset_cls_test
|
| 113 |
+
from detic.modeling.text.text_encoder import build_text_encoder
|
| 114 |
+
|
| 115 |
+
class LVISPredictor(DefaultPredictor):
|
| 116 |
+
def __init__(self, cfg, vocab, custom_vocabulary=None, instance_mode=ColorMode.IMAGE):
|
| 117 |
+
"""
|
| 118 |
+
Args:
|
| 119 |
+
cfg (CfgNode):
|
| 120 |
+
instance_mode (ColorMode):
|
| 121 |
+
parallel (bool): whether to run the model in different processes from visualization.
|
| 122 |
+
Useful since the visualization logic can be slow.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
self.BUILDIN_CLASSIFIER = {
|
| 126 |
+
"lvis": "modules/Detic/datasets/metadata/lvis_v1_clip_a+cname.npy",
|
| 127 |
+
"objects365": "modules/Detic/datasets/metadata/o365_clip_a+cnamefix.npy",
|
| 128 |
+
"openimages": "modules/Detic/datasets/metadata/oid_clip_a+cname.npy",
|
| 129 |
+
"coco": "modules/Detic/datasets/metadata/coco_clip_a+cname.npy",
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
self.BUILDIN_METADATA_PATH = {
|
| 133 |
+
"lvis": "lvis_v1_val",
|
| 134 |
+
"objects365": "objects365_v2_val",
|
| 135 |
+
"openimages": "oid_val_expanded",
|
| 136 |
+
"coco": "coco_2017_val",
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
if vocab == "custom":
|
| 140 |
+
self.metadata = MetadataCatalog.get("__unused")
|
| 141 |
+
self.metadata.thing_classes = custom_vocabulary.split(',')
|
| 142 |
+
classifier = get_clip_embeddings(self.metadata.thing_classes)
|
| 143 |
+
else:
|
| 144 |
+
self.metadata = MetadataCatalog.get(
|
| 145 |
+
self.BUILDIN_METADATA_PATH[vocab])
|
| 146 |
+
classifier = self.BUILDIN_CLASSIFIER[vocab]
|
| 147 |
+
|
| 148 |
+
num_classes = len(self.metadata.thing_classes)
|
| 149 |
+
self.cpu_device = torch.device("cpu")
|
| 150 |
+
self.instance_mode = instance_mode
|
| 151 |
+
|
| 152 |
+
self.predictor = DefaultPredictor(cfg)
|
| 153 |
+
reset_cls_test(self.predictor.model, classifier, num_classes)
|
| 154 |
+
|
| 155 |
+
def __call__(self, image):
|
| 156 |
+
"""
|
| 157 |
+
Args:
|
| 158 |
+
image (np.ndarray): an image of shape (H, W, C) (in BGR order).
|
| 159 |
+
This is the format used by OpenCV.
|
| 160 |
+
|
| 161 |
+
Returns:
|
| 162 |
+
predictions (dict): the output of the model.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
predictions = self.predictor(image)
|
| 166 |
+
|
| 167 |
+
return predictions
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def get_clip_embeddings(vocabulary, prompt='a '):
|
| 171 |
+
text_encoder = build_text_encoder(pretrain=True)
|
| 172 |
+
text_encoder.eval()
|
| 173 |
+
texts = [prompt + x for x in vocabulary]
|
| 174 |
+
emb = text_encoder(texts).detach().permute(1, 0).contiguous().cpu()
|
| 175 |
+
return emb
|
| 176 |
+
|
| 177 |
+
# download model weights
|
| 178 |
+
model_path = "models/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth"
|
| 179 |
+
model_url = "https://dl.fbaipublicfiles.com/detic/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth"
|
| 180 |
+
|
| 181 |
+
if not os.path.exists(model_path):
|
| 182 |
+
print("Download model weights")
|
| 183 |
+
r = requests.get(model_url)
|
| 184 |
+
with open(model_path, "wb") as f:
|
| 185 |
+
f.write(r.content)
|
| 186 |
+
|
| 187 |
+
# config
|
| 188 |
+
cfg_lvis = get_cfg() # weight-file
|
| 189 |
+
add_centernet_config(cfg_lvis)
|
| 190 |
+
add_detic_config(cfg_lvis)
|
| 191 |
+
cfg_lvis.merge_from_file("modules/Detic/configs/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.yaml")
|
| 192 |
+
cfg_lvis.MODEL.WEIGHTS = "models/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth"
|
| 193 |
+
cfg_lvis.MODEL.ROI_BOX_HEAD.CAT_FREQ_PATH = "modules/Detic/datasets/metadata/lvis_v1_train_cat_info.json"
|
| 194 |
+
cfg_lvis.MODEL.ROI_BOX_HEAD.ZEROSHOT_WEIGHT_PATH = "rand" # load later
|
| 195 |
+
cfg_lvis.MODEL.ROI_HEADS.ONE_CLASS_PER_PROPOSAL = True
|
| 196 |
+
cfg_lvis.freeze()
|
| 197 |
+
# predictor
|
| 198 |
+
predictor_lvis = LVISPredictor(cfg_lvis, vocab="lvis")
|
| 199 |
+
|
| 200 |
+
else:
|
| 201 |
+
# get coco model
|
| 202 |
+
print("Get model for vocabulary COCO")
|
| 203 |
+
|
| 204 |
+
# config
|
| 205 |
+
cfg_coco = get_cfg()
|
| 206 |
+
# device
|
| 207 |
+
cfg_coco.MODEL.DEVICE = "cpu"
|
| 208 |
+
# add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
|
| 209 |
+
cfg_coco.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml"))
|
| 210 |
+
cfg_coco.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.1 # set threshold for this model
|
| 211 |
+
# Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
|
| 212 |
+
cfg_coco.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml")
|
| 213 |
+
|
| 214 |
+
# predictor
|
| 215 |
+
predictor_coco = DefaultPredictor(cfg_coco)
|
| 216 |
+
|
| 217 |
+
# get coco model
|
| 218 |
+
print("Get model for vocabulary LVIS")
|
| 219 |
+
|
| 220 |
+
# config
|
| 221 |
+
cfg_lvis = get_cfg()
|
| 222 |
+
# device
|
| 223 |
+
cfg_lvis.MODEL.DEVICE = "cpu"
|
| 224 |
+
# add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
|
| 225 |
+
cfg_lvis.merge_from_file(model_zoo.get_config_file("LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml"))
|
| 226 |
+
cfg_lvis.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.1 # set threshold for this model
|
| 227 |
+
# Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
|
| 228 |
+
cfg_lvis.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml")
|
| 229 |
+
|
| 230 |
+
# predictor
|
| 231 |
+
predictor_lvis = DefaultPredictor(cfg_lvis)
|
| 232 |
+
|
| 233 |
+
return predictor_coco, cfg_coco, predictor_lvis, cfg_lvis
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def predict(image, vocabulary, feature_aggregation):
|
| 237 |
+
"""
|
| 238 |
+
Predict segmented image and feature vector
|
| 239 |
+
|
| 240 |
+
:param image:
|
| 241 |
+
:param vocabulary:
|
| 242 |
+
:param feature_aggregation:
|
| 243 |
+
:return:
|
| 244 |
"""
|
| 245 |
|
| 246 |
+
# convert image and resize if necessary
|
| 247 |
+
image = image.convert('RGB')
|
| 248 |
+
image.thumbnail((2000, 2000), Image.LANCZOS)
|
| 249 |
+
image = np.array(image)
|
| 250 |
+
|
| 251 |
+
# check vocabulary
|
| 252 |
+
if vocabulary == "COCO":
|
| 253 |
+
# get predictions
|
| 254 |
+
predictions = predictor_coco(image)
|
| 255 |
+
|
| 256 |
+
# visualize predictions
|
| 257 |
+
visualizer = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg_coco.DATASETS.TRAIN[0]), instance_mode=ColorMode.SEGMENTATION)
|
| 258 |
+
image_segmented = visualizer.draw_instance_predictions(predictions["instances"].to("cpu"))
|
| 259 |
+
image_segmented = Image.fromarray(image_segmented.get_image()[:, :, ::-1])
|
| 260 |
+
|
| 261 |
+
# get class names
|
| 262 |
+
class_names = {class_num: class_name.lower() for class_num, class_name in enumerate(MetadataCatalog.get(cfg_coco.DATASETS.TRAIN[0]).thing_classes)}
|
| 263 |
+
|
| 264 |
+
elif vocabulary == "LVIS":
|
| 265 |
+
# get predictions
|
| 266 |
+
predictions = predictor_lvis(image)
|
| 267 |
+
|
| 268 |
+
# visualize predictions
|
| 269 |
+
visualizer = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg_lvis.DATASETS.TRAIN[0]), instance_mode=ColorMode.SEGMENTATION)
|
| 270 |
+
image_segmented = visualizer.draw_instance_predictions(predictions["instances"].to("cpu"))
|
| 271 |
+
image_segmented = Image.fromarray(image_segmented.get_image()[:, :, ::-1])
|
| 272 |
+
|
| 273 |
+
# get class names
|
| 274 |
+
class_names = {class_num: class_name.lower() for class_num, class_name in enumerate(MetadataCatalog.get(cfg_lvis.DATASETS.TRAIN[0]).thing_classes)}
|
| 275 |
+
|
| 276 |
+
else:
|
| 277 |
+
raise Exception("Unknown vocabulary")
|
| 278 |
+
|
| 279 |
+
# prepare segments in long format
|
| 280 |
+
segments_long_df = pd.DataFrame([])
|
| 281 |
+
|
| 282 |
+
for seg_num, seg_score, seg_mask in zip(predictions["instances"].pred_classes, predictions["instances"].scores, predictions["instances"].pred_masks):
|
| 283 |
+
segments_long_df = pd.concat([segments_long_df, pd.Series({
|
| 284 |
+
"id": "image_1",
|
| 285 |
+
"seg_num": seg_num.item(),
|
| 286 |
+
"seg_name": class_names[seg_num.item()],
|
| 287 |
+
"seg_score": seg_score.item(),
|
| 288 |
+
"seg_prop": (torch.sum(seg_mask == True) / torch.numel(seg_mask)).item()
|
| 289 |
+
}).to_frame().T], ignore_index=True)
|
| 290 |
+
|
| 291 |
+
# TODO: delete segments with less than 0.1
|
| 292 |
+
#segments_long_df = segments_long_df.loc[(segments_long_df["seg_score"] >= 0.1)].reset_index(drop=True)
|
| 293 |
+
|
| 294 |
+
if feature_aggregation == "bin":
|
| 295 |
+
# get segments wide
|
| 296 |
+
segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_score"], aggfunc={"seg_score": ["any"]})
|
| 297 |
+
cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
|
| 298 |
+
cols_missing = [f'{vocabulary.lower()}_{category.lower()}_bin' for category in cols_missing]
|
| 299 |
+
segments_wide_df.columns = [f'{vocabulary.lower()}_{label.lower()}_bin' for var, agg, label in segments_wide_df.columns]
|
| 300 |
+
segments_wide_df = segments_wide_df.reset_index()
|
| 301 |
+
segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
|
| 302 |
+
segments_wide_df = segments_wide_df.fillna(0)
|
| 303 |
+
# get cols
|
| 304 |
+
cols = [f'{vocabulary.lower()}_{cat.lower()}_bin' for cat in class_names.values()]
|
| 305 |
+
# get vector
|
| 306 |
+
feature_vector = segments_wide_df.loc[:, cols].astype(int).to_json(orient="records")
|
| 307 |
+
|
| 308 |
+
elif feature_aggregation == "count":
|
| 309 |
+
segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_score"], aggfunc={"seg_score": ["count"]})
|
| 310 |
+
cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
|
| 311 |
+
cols_missing = [f'{vocabulary.lower()}_{category.lower()}_count' for category in cols_missing]
|
| 312 |
+
segments_wide_df.columns = [f'{vocabulary.lower()}_{label.lower()}_count' for var, agg, label in segments_wide_df.columns]
|
| 313 |
+
segments_wide_df = segments_wide_df.reset_index()
|
| 314 |
+
segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
|
| 315 |
+
segments_wide_df = segments_wide_df.fillna(0)
|
| 316 |
+
# get cols
|
| 317 |
+
cols = [f'{vocabulary.lower()}_{cat.lower()}_count' for cat in class_names.values()]
|
| 318 |
+
# get vector
|
| 319 |
+
feature_vector = segments_wide_df.loc[:, cols].astype(int).to_json(orient="records")
|
| 320 |
+
|
| 321 |
+
elif feature_aggregation == "area_max":
|
| 322 |
+
segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_prop"], aggfunc={"seg_prop": ["max"]})
|
| 323 |
+
cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
|
| 324 |
+
cols_missing = [f"{vocabulary.lower()}_{category.lower()}_area_max" for category in cols_missing]
|
| 325 |
+
segments_wide_df.columns = [f"{vocabulary.lower()}_{label.lower()}_area_max" for var, agg, label in segments_wide_df.columns]
|
| 326 |
+
segments_wide_df = segments_wide_df.reset_index()
|
| 327 |
+
segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
|
| 328 |
+
segments_wide_df = segments_wide_df.fillna(0)
|
| 329 |
+
# get cols
|
| 330 |
+
cols = [f"{vocabulary.lower()}_{cat.lower()}_area_max" for cat in class_names.values()]
|
| 331 |
+
# get vector
|
| 332 |
+
feature_vector = segments_wide_df.loc[:, cols].astype(float).to_json(orient="records")
|
| 333 |
+
|
| 334 |
+
elif feature_aggregation == "area_sum":
|
| 335 |
+
segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_prop"], aggfunc={"seg_prop": ["sum"]})
|
| 336 |
+
cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]]
|
| 337 |
+
cols_missing = [f"{vocabulary.lower()}_{category.lower()}_area_sum" for category in cols_missing]
|
| 338 |
+
segments_wide_df.columns = [f"{vocabulary.lower()}_{label.lower()}_area_sum" for var, agg, label in segments_wide_df.columns]
|
| 339 |
+
segments_wide_df = segments_wide_df.reset_index()
|
| 340 |
+
segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing])
|
| 341 |
+
segments_wide_df = segments_wide_df.fillna(0)
|
| 342 |
+
# get cols
|
| 343 |
+
cols = [f"{vocabulary.lower()}_{cat.lower()}_area_sum" for cat in class_names.values()]
|
| 344 |
+
# get vector
|
| 345 |
+
feature_vector = segments_wide_df.loc[:, cols].astype(float).to_json(orient="records")
|
| 346 |
+
|
| 347 |
+
return image_segmented, feature_vector
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
# get models
|
| 351 |
+
predictor_coco, cfg_coco, predictor_lvis, cfg_lvis = get_models()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
# define app interface
|
| 354 |
app = gr.Interface(
|