#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Application for demo space """ import os import sys import torch import requests import numpy as np import pandas as pd import gradio as gr from PIL import Image from detectron2 import model_zoo from detectron2.config import get_cfg from detectron2.data import MetadataCatalog from detectron2.engine import DefaultPredictor from detectron2.utils.visualizer import ColorMode, Visualizer from detectron2.projects.deeplab import add_deeplab_config, build_lr_scheduler def get_article(): """ Get article :return: """ if torch.cuda.is_available(): article = """ The space demonstrates the method introduced in the paper 'Improving Computer Vision Interpretability: Transparent Two-level Classification for Complex Scenes'. The segments from the COCO vocabulary are recognized with the segmentation model by [Li et al. (2022)](https://arxiv.org/abs/2206.02777), while they are recognized from the LVIS vocabulary with the model by [Zhou et al (2022)](https://arxiv.org/abs/2201.02605). """ else: article = """ The space demonstrates the method introduced in the paper 'Improving Computer Vision Interpretability: Transparent Two-level Classification for Complex Scenes'. ⚠️ The segments from the COCO vocabulary as well as the LVIS v0.5 vocabulary are recognized with the segmentation model by [Wu et al., 2017](https://github.com/facebookresearch/detectron2/tree/main). If you want to use the same segmentation models as in the paper, then you have to duplicate this space in a space environment with GPU accelerator. """ return article def get_models(): """ Get article :return: """ if torch.cuda.is_available(): # get coco model print("Get model for vocabulary COCO") # import modules only available with gpu sys.path.insert(0, "./modules/MaskDINO") from maskdino import add_maskformer2_config # download model weights model_path = "models/maskdino_swinl_50ep_300q_hid2048_3sd1_instance_maskenhanced_mask52.3ap_box59.0ap.pth" 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" if not os.path.exists(model_path): print("Download model weights for vocabulary COCO") r = requests.get(model_url) with open(model_path, "wb") as f: f.write(r.content) # config cfg_coco = get_cfg() # for poly lr schedule add_deeplab_config(cfg_coco) add_maskformer2_config(cfg_coco) cfg_coco.merge_from_file("modules/MaskDINO/configs/coco/instance-segmentation/swin/maskdino_R50_bs16_50ep_4s_dowsample1_2048.yaml") cfg_coco.MODEL.WEIGHTS = "models/maskdino_swinl_50ep_300q_hid2048_3sd1_instance_maskenhanced_mask52.3ap_box59.0ap.pth" cfg_coco.MODEL.RETINANET.SCORE_THRESH_TEST = 0.0 # no effect cfg_coco.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.0 # no effect cfg_coco.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = 0.0 # no effect cfg_coco.freeze() # predictor predictor_coco = DefaultPredictor(cfg_coco) # get lvis model print("Get model for vocabulary LVIS") # import modules only available with gpu sys.path.insert(0, "./modules/Detic") sys.path.insert(0, "./modules/Detic/third_party/CenterNet2") from centernet.config import add_centernet_config from detic.config import add_detic_config from detic.modeling.utils import reset_cls_test from detic.modeling.text.text_encoder import build_text_encoder class LVISPredictor(DefaultPredictor): def __init__(self, cfg, vocab, custom_vocabulary=None, instance_mode=ColorMode.IMAGE): """ Args: cfg (CfgNode): instance_mode (ColorMode): parallel (bool): whether to run the model in different processes from visualization. Useful since the visualization logic can be slow. """ self.BUILDIN_CLASSIFIER = { "lvis": "modules/Detic/datasets/metadata/lvis_v1_clip_a+cname.npy", "objects365": "modules/Detic/datasets/metadata/o365_clip_a+cnamefix.npy", "openimages": "modules/Detic/datasets/metadata/oid_clip_a+cname.npy", "coco": "modules/Detic/datasets/metadata/coco_clip_a+cname.npy", } self.BUILDIN_METADATA_PATH = { "lvis": "lvis_v1_val", "objects365": "objects365_v2_val", "openimages": "oid_val_expanded", "coco": "coco_2017_val", } if vocab == "custom": self.metadata = MetadataCatalog.get("__unused") self.metadata.thing_classes = custom_vocabulary.split(',') classifier = get_clip_embeddings(self.metadata.thing_classes) else: self.metadata = MetadataCatalog.get( self.BUILDIN_METADATA_PATH[vocab]) classifier = self.BUILDIN_CLASSIFIER[vocab] num_classes = len(self.metadata.thing_classes) self.cpu_device = torch.device("cpu") self.instance_mode = instance_mode self.predictor = DefaultPredictor(cfg) reset_cls_test(self.predictor.model, classifier, num_classes) def __call__(self, image): """ Args: image (np.ndarray): an image of shape (H, W, C) (in BGR order). This is the format used by OpenCV. Returns: predictions (dict): the output of the model. """ predictions = self.predictor(image) return predictions def get_clip_embeddings(vocabulary, prompt='a '): text_encoder = build_text_encoder(pretrain=True) text_encoder.eval() texts = [prompt + x for x in vocabulary] emb = text_encoder(texts).detach().permute(1, 0).contiguous().cpu() return emb # download model weights model_path = "models/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth" model_url = "https://dl.fbaipublicfiles.com/detic/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth" if not os.path.exists(model_path): print("Download model weights") r = requests.get(model_url) with open(model_path, "wb") as f: f.write(r.content) # config cfg_lvis = get_cfg() # weight-file add_centernet_config(cfg_lvis) add_detic_config(cfg_lvis) cfg_lvis.merge_from_file("modules/Detic/configs/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.yaml") cfg_lvis.MODEL.WEIGHTS = "models/Detic_LCOCOI21k_CLIP_SwinB_896b32_4x_ft4x_max-size.pth" cfg_lvis.MODEL.ROI_BOX_HEAD.CAT_FREQ_PATH = "modules/Detic/datasets/metadata/lvis_v1_train_cat_info.json" cfg_lvis.MODEL.ROI_BOX_HEAD.ZEROSHOT_WEIGHT_PATH = "rand" # load later cfg_lvis.MODEL.ROI_HEADS.ONE_CLASS_PER_PROPOSAL = True cfg_lvis.freeze() # predictor predictor_lvis = LVISPredictor(cfg_lvis, vocab="lvis") else: # get coco model print("Get model for vocabulary COCO") # config cfg_coco = get_cfg() # device cfg_coco.MODEL.DEVICE = "cpu" # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library cfg_coco.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml")) cfg_coco.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.1 # set threshold for this model # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well cfg_coco.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml") # predictor predictor_coco = DefaultPredictor(cfg_coco) # get coco model print("Get model for vocabulary LVIS") # config cfg_lvis = get_cfg() # device cfg_lvis.MODEL.DEVICE = "cpu" # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library cfg_lvis.merge_from_file(model_zoo.get_config_file("LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml")) cfg_lvis.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.1 # set threshold for this model # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well cfg_lvis.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x.yaml") # predictor predictor_lvis = DefaultPredictor(cfg_lvis) return predictor_coco, cfg_coco, predictor_lvis, cfg_lvis def predict(image, vocabulary, feature_aggregation): """ Predict segmented image and feature vector :param image: :param vocabulary: :param feature_aggregation: :return: """ # convert image and resize if necessary image = image.convert('RGB') image.thumbnail((2000, 2000), Image.LANCZOS) image = np.array(image) # check vocabulary if vocabulary == "COCO": # get predictions predictions = predictor_coco(image) # visualize predictions visualizer = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg_coco.DATASETS.TRAIN[0]), instance_mode=ColorMode.SEGMENTATION) image_segmented = visualizer.draw_instance_predictions(predictions["instances"].to("cpu")) image_segmented = Image.fromarray(image_segmented.get_image()[:, :, ::-1]) # get class names class_names = {class_num: class_name.lower() for class_num, class_name in enumerate(MetadataCatalog.get(cfg_coco.DATASETS.TRAIN[0]).thing_classes)} elif vocabulary == "LVIS": # get predictions predictions = predictor_lvis(image) # visualize predictions visualizer = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg_lvis.DATASETS.TRAIN[0]), instance_mode=ColorMode.SEGMENTATION) image_segmented = visualizer.draw_instance_predictions(predictions["instances"].to("cpu")) image_segmented = Image.fromarray(image_segmented.get_image()[:, :, ::-1]) # get class names class_names = {class_num: class_name.lower() for class_num, class_name in enumerate(MetadataCatalog.get(cfg_lvis.DATASETS.TRAIN[0]).thing_classes)} else: raise Exception("Unknown vocabulary") # prepare segments in long format segments_long_df = pd.DataFrame([]) for seg_num, seg_score, seg_mask in zip(predictions["instances"].pred_classes, predictions["instances"].scores, predictions["instances"].pred_masks): segments_long_df = pd.concat([segments_long_df, pd.Series({ "id": "image_1", "seg_num": seg_num.item(), "seg_name": class_names[seg_num.item()], "seg_score": seg_score.item(), "seg_prop": (torch.sum(seg_mask == True) / torch.numel(seg_mask)).item() }).to_frame().T], ignore_index=True) # TODO: delete segments with less than 0.1 #segments_long_df = segments_long_df.loc[(segments_long_df["seg_score"] >= 0.1)].reset_index(drop=True) if feature_aggregation == "bin": # get segments wide segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_score"], aggfunc={"seg_score": ["any"]}) cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]] cols_missing = [f'{vocabulary.lower()}_{category.lower()}_bin' for category in cols_missing] segments_wide_df.columns = [f'{vocabulary.lower()}_{label.lower()}_bin' for var, agg, label in segments_wide_df.columns] segments_wide_df = segments_wide_df.reset_index() segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing]) segments_wide_df = segments_wide_df.fillna(0) # get cols cols = [f'{vocabulary.lower()}_{cat.lower()}_bin' for cat in class_names.values()] # get vector feature_vector = segments_wide_df.loc[:, cols].astype(int).to_json(orient="records") elif feature_aggregation == "count": segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_score"], aggfunc={"seg_score": ["count"]}) cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]] cols_missing = [f'{vocabulary.lower()}_{category.lower()}_count' for category in cols_missing] segments_wide_df.columns = [f'{vocabulary.lower()}_{label.lower()}_count' for var, agg, label in segments_wide_df.columns] segments_wide_df = segments_wide_df.reset_index() segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing]) segments_wide_df = segments_wide_df.fillna(0) # get cols cols = [f'{vocabulary.lower()}_{cat.lower()}_count' for cat in class_names.values()] # get vector feature_vector = segments_wide_df.loc[:, cols].astype(int).to_json(orient="records") elif feature_aggregation == "area_max": segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_prop"], aggfunc={"seg_prop": ["max"]}) cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]] cols_missing = [f"{vocabulary.lower()}_{category.lower()}_area_max" for category in cols_missing] segments_wide_df.columns = [f"{vocabulary.lower()}_{label.lower()}_area_max" for var, agg, label in segments_wide_df.columns] segments_wide_df = segments_wide_df.reset_index() segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing]) segments_wide_df = segments_wide_df.fillna(0) # get cols cols = [f"{vocabulary.lower()}_{cat.lower()}_area_max" for cat in class_names.values()] # get vector feature_vector = segments_wide_df.loc[:, cols].astype(float).to_json(orient="records") elif feature_aggregation == "area_sum": segments_wide_df = segments_long_df.pivot_table(index=["id"], columns=["seg_name"], values=["seg_prop"], aggfunc={"seg_prop": ["sum"]}) cols_missing = [category for category in class_names.values() if category not in [label for agg, var, label in segments_wide_df.columns]] cols_missing = [f"{vocabulary.lower()}_{category.lower()}_area_sum" for category in cols_missing] segments_wide_df.columns = [f"{vocabulary.lower()}_{label.lower()}_area_sum" for var, agg, label in segments_wide_df.columns] segments_wide_df = segments_wide_df.reset_index() segments_wide_df = segments_wide_df.reindex(columns=segments_wide_df.columns.tolist() + [column for column in cols_missing]) segments_wide_df = segments_wide_df.fillna(0) # get cols cols = [f"{vocabulary.lower()}_{cat.lower()}_area_sum" for cat in class_names.values()] # get vector feature_vector = segments_wide_df.loc[:, cols].astype(float).to_json(orient="records") return image_segmented, feature_vector if __name__ == "__main__": # get models predictor_coco, cfg_coco, predictor_lvis, cfg_lvis = get_models() # define interface app = gr.Interface( predict, inputs=[ gr.Image(label="Select image", sources=["upload", "webcam"], type="pil"), gr.Dropdown(label="Select vocabulary", choices=["COCO", "LVIS"]), gr.Dropdown(label="Select feature aggregation", choices=["bin", "count", "area_max", "area_sum"]), ], outputs=[ gr.Image(label="Segmented Image"), gr.JSON(label="Feature Vector") ], title="Protest Segments: What is the Feature Vector of My Image?", article = get_article() ) # create queue app.queue( max_size=100, default_concurrency_limit=1, ) # launch app.launch( server_name="0.0.0.0", server_port=7860, )