Denis Arkusha commited on
Commit
cd3ce82
·
1 Parent(s): 4d3dd7f

1-st commit

Browse files
Files changed (10) hide show
  1. Dockerfile +58 -0
  2. README.md +133 -8
  3. _wsgi.py +115 -0
  4. data/ml-backend/models/cache.db +0 -0
  5. dino.py +450 -0
  6. docker-compose.yml +46 -0
  7. requirements-test.txt +2 -0
  8. requirements.txt +9 -0
  9. start.sh +4 -0
  10. test_api.py +5 -0
Dockerfile ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM pytorch/pytorch:2.1.2-cuda12.1-cudnn8-runtime
2
+ ARG DEBIAN_FRONTEND=noninteractive
3
+ ARG TEST_ENV
4
+
5
+ WORKDIR /app
6
+
7
+ RUN conda update conda -y
8
+
9
+ RUN --mount=type=cache,target="/var/cache/apt",sharing=locked \
10
+ --mount=type=cache,target="/var/lib/apt/lists",sharing=locked \
11
+ apt-get -y update \
12
+ && apt-get install -y git \
13
+ && apt-get install -y wget \
14
+ && apt-get install -y g++ freeglut3-dev build-essential libx11-dev \
15
+ libxmu-dev libxi-dev libglu1-mesa libglu1-mesa-dev libfreeimage-dev \
16
+ && apt-get -y install ffmpeg libsm6 libxext6 libffi-dev python3-dev python3-pip gcc
17
+
18
+ ENV PYTHONUNBUFFERED=1 \
19
+ PYTHONDONTWRITEBYTECODE=1 \
20
+ PIP_CACHE_DIR=/.cache \
21
+ PORT=9090 \
22
+ WORKERS=2 \
23
+ THREADS=4 \
24
+ CUDA_HOME=/usr/local/cuda \
25
+ GROUNDINGDINO_REPO_PATH=/GroundingDINO
26
+
27
+ RUN conda install -c "nvidia/label/cuda-12.1.1" cuda -y
28
+ ENV CUDA_HOME=/opt/conda \
29
+ TORCH_CUDA_ARCH_LIST="6.0;6.1;7.0;7.5;8.0;8.6+PTX;8.9;9.0"
30
+
31
+ COPY requirements.txt .
32
+ RUN --mount=type=cache,target=${PIP_CACHE_DIR},sharing=locked \
33
+ pip3 install --no-cache-dir -r requirements.txt
34
+
35
+ # install GroundingDINO
36
+ RUN cd / && git clone https://github.com/IDEA-Research/GroundingDINO.git
37
+ WORKDIR /GroundingDINO
38
+ RUN --mount=type=cache,target=${PIP_CACHE_DIR},sharing=locked \
39
+ pip3 install -e .
40
+ RUN mkdir weights
41
+ WORKDIR /GroundingDINO/weights
42
+ RUN wget -q https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
43
+
44
+ WORKDIR /app
45
+ RUN wget -q https://github.com/ChaoningZhang/MobileSAM/raw/master/weights/mobile_sam.pt
46
+ RUN wget -q https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
47
+
48
+ # install test requirements if needed
49
+ COPY requirements-test.txt .
50
+ # build only when TEST_ENV="true"
51
+ RUN --mount=type=cache,target=${PIP_CACHE_DIR},sharing=locked \
52
+ if [ "$TEST_ENV" = "true" ]; then \
53
+ pip3 install -r requirements-test.txt; \
54
+ fi
55
+
56
+ COPY . ./
57
+
58
+ CMD ["/app/start.sh"]
README.md CHANGED
@@ -1,11 +1,136 @@
 
1
  ---
2
- title: Saml
3
- emoji: 🐨
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- pinned: false
8
- license: mit
 
 
 
 
 
 
 
 
 
9
  ---
 
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--
2
  ---
3
+ title: Zero-shot object detection and image segmentation with Grounding DINO and SAM
4
+ type: guide
5
+ tier: all
6
+ order: 15
7
+ hide_menu: true
8
+ hide_frontmatter_title: true
9
+ meta_title: Image segmentation in Label Studio using a Grounding DINO backend and SAM
10
+ meta_description: Label Studio tutorial for using Grounding DINO and SAM for zero-shot object detection in images
11
+ categories:
12
+ - Computer Vision
13
+ - Image Annotation
14
+ - Object Detection
15
+ - Zero-shot Image Segmentation
16
+ - Grounding DINO
17
+ - Segment Anything Model
18
+ image: "/tutorials/grounding-sam.png"
19
  ---
20
+ -->
21
 
22
+ https://github.com/HumanSignal/label-studio-ml-backend/assets/106922533/d1d2f233-d7c0-40ac-ba6f-368c3c01fd36
23
+
24
+
25
+ # Grounding DINO backend integration with SAM enabled
26
+
27
+ This integration will allow you to:
28
+
29
+ * Use text prompts for zero-shot detection of objects in images.
30
+ * Specify the detection of any object and get state-of-the-art results without any model fine tuning.
31
+ * Get segmentation predictions from SAM with just text prompts.
32
+
33
+ See [here](https://github.com/IDEA-Research/GroundingDINO) for more details about the pre-trained Grounding DINO model.
34
+
35
+ ## Before you begin
36
+
37
+ Before you begin, you must install the [Label Studio ML backend](https://github.com/HumanSignal/label-studio-ml-backend?tab=readme-ov-file#quickstart).
38
+
39
+ This tutorial uses the [`grounding_sam` example](https://github.com/HumanSignal/label-studio-ml-backend/tree/master/label_studio_ml/examples/grounding_sam).
40
+
41
+
42
+ ## Quickstart
43
+
44
+ 1. Make sure Docker is installed.
45
+ 2. Edit `docker-compose.yml` to include the following:
46
+ * `LABEL_STUDIO_HOST` sets the endpoint of the Label Studio host. Must begin with `http://`
47
+ * `LABEL_STUDIO_ACCESS_TOKEN` sets the API access token for the Label Studio host. This can be found by logging
48
+ into Label Studio and [going to the **Account & Settings** page](https://labelstud.io/guide/user_account#Access-token).
49
+
50
+ Example:
51
+ - `LABEL_STUDIO_HOST=http://123.456.7.8:8080`
52
+ - `LABEL_STUDIO_ACCESS_TOKEN=your-api-key`
53
+
54
+ 3. Run `docker compose up`
55
+ 4. Check the IP of your backend using `docker ps`. You will use this URL when connecting the backend to a Label Studio project. Usually this is `http://localhost:9090`.
56
+
57
+ 5. Create a project and edit the labeling config (an example is provided below). When editing the labeling config, make sure to add all rectangle labels under the `RectangleLabels` tag, and all corresponding brush labels under the `BrushLabels` tag.
58
+
59
+ ```xml
60
+ <View>
61
+ <Image name="image" value="$image"/>
62
+ <Style>
63
+ .lsf-main-content.lsf-requesting .prompt::before { content: ' loading...'; color: #808080; }
64
+ </Style>
65
+ <View className="prompt">
66
+ <TextArea name="prompt" toName="image" editable="true" rows="2" maxSubmissions="1" showSubmitButton="true"/>
67
+ </View>
68
+ <RectangleLabels name="label" toName="image">
69
+ <Label value="cats" background="yellow"/>
70
+ <Label value="house" background="blue"/>
71
+ </RectangleLabels>
72
+ <BrushLabels name="label2" toName="image">
73
+ <Label value="cats" background="yellow"/>
74
+ <Label value="house" background="blue"/>
75
+ </BrushLabels>
76
+ </View>
77
+ ```
78
+
79
+ 6. From the **Model** page in the project settings, [connect the model](https://labelstud.io/guide/ml#Connect-the-model-to-Label-Studio).
80
+ 7. Go to an image task in your project. Enable **Auto-annotation** (found at the bottom of the labeling interface). Then enter in the prompt box and press **Add**. After this, you should receive your predictions. See the video above for a demo.
81
+
82
+
83
+ ## Using GPU
84
+
85
+ For the best user experience, it is recommended to use a GPU. To do this, you can update the `docker-compose.yml` file including the following lines:
86
+
87
+ ```yaml
88
+ environment:
89
+ - NVIDIA_VISIBLE_DEVICES=all
90
+ deploy:
91
+ resources:
92
+ reservations:
93
+ devices:
94
+ - driver: nvidia
95
+ count: 1
96
+ capabilities: [gpu]
97
+ ```
98
+
99
+ ## Using GroundingSAM
100
+
101
+ Combine the Segment Anything Model with your text input to automatically generate mask predictions!
102
+
103
+ To do this, set `USE_SAM=true` before running.
104
+
105
+ > Warning: Using GroundingSAM without a GPU may result in slow performance and is not recommended. If you must use a CPU-only machine, and experience slow performance or don't see any predictions on the labeling screen, consider one of the following:
106
+ > - Increase memory allocated to the Docker container (e.g. `memory: 16G` in `docker-compose.yml`)
107
+ > - Increase the prediction timeout on Label Studio instance with the `ML_TIMEOUT_PREDICT=100` environment variable.
108
+ > - Use "MobileSAM" as a lightweight alternative to "SAM".
109
+
110
+ If you want to use a [more efficient version of SAM](https://github.com/ChaoningZhang/MobileSAM), set `USE_MOBILE_SAM=true`.
111
+
112
+
113
+ ## Batching inputs
114
+
115
+ https://github.com/HumanSignal/label-studio-ml-backend/assets/106922533/79b788e3-9147-47c0-90db-0404066ee43f
116
+
117
+ > Note: This is an experimental feature.
118
+
119
+ 1. Clone the Label Studio feature branch that includes the experimental batching functionality.
120
+
121
+ `git clone -b feature/dino-support https://github.com/HumanSignal/label-studio.git`
122
+
123
+ 2. Run this branch with `docker compose up`
124
+ 3. Do steps 2-5 from the [quickstart section](#quickstart), now using access code and host IP info of the newly cloned Label Studio branch. GroundingSAM is supported.
125
+ 4. Go to the Data Manager in your project and select the tasks you would like to annotate.
126
+ 5. Select **Actions > Add Text Prompt for GroundingDINO**.
127
+ 6. Enter the prompt you would like to retrieve predictions for and click **Submit**.
128
+
129
+ > Note: If your prompt is different from the label values you have assigned, you can use the underscore to give the correct label values to your prompt outputs. For example, if you wanted to select all brown cats but still give them the label value "cats" from your labeling config, your prompt would be "brown cat_cats".
130
+
131
+
132
+ ## Other environment variables
133
+
134
+ Adjust `BOX_THRESHOLD` and `TEXT_THRESHOLD` values in the Dockerfile to a number between 0 to 1 if experimenting. Defaults are set in `dino.py`. For more information about these values, [click here](https://github.com/IDEA-Research/GroundingDINO#star-explanationstips-for-grounding-dino-inputs-and-outputs).
135
+
136
+ If you want to use SAM models saved from either directories, you can use the `MOBILESAM_CHECKPOINT` and `SAM_CHECKPOINT` as shown in the Dockerfile.
_wsgi.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import json
4
+ import logging
5
+ import logging.config
6
+
7
+ logging.config.dictConfig({
8
+ "version": 1,
9
+ "disable_existing_loggers": False,
10
+ "formatters": {
11
+ "standard": {
12
+ "format": "[%(asctime)s] [%(levelname)s] [%(name)s::%(funcName)s::%(lineno)d] %(message)s"
13
+ }
14
+ },
15
+ "handlers": {
16
+ "console": {
17
+ "class": "logging.StreamHandler",
18
+ "level": os.getenv('LOG_LEVEL'),
19
+ "stream": "ext://sys.stdout",
20
+ "formatter": "standard"
21
+ }
22
+ },
23
+ "root": {
24
+ "level": os.getenv('LOG_LEVEL'),
25
+ "handlers": [
26
+ "console"
27
+ ],
28
+ "propagate": True
29
+ }
30
+ })
31
+
32
+ from label_studio_ml.api import init_app
33
+ from dino import DINOBackend
34
+
35
+
36
+ _DEFAULT_CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'config.json')
37
+
38
+
39
+ def get_kwargs_from_config(config_path=_DEFAULT_CONFIG_PATH):
40
+ if not os.path.exists(config_path):
41
+ return dict()
42
+ with open(config_path) as f:
43
+ config = json.load(f)
44
+ assert isinstance(config, dict)
45
+ return config
46
+
47
+
48
+ if __name__ == "__main__":
49
+ parser = argparse.ArgumentParser(description='Label studio')
50
+ parser.add_argument(
51
+ '-p', '--port', dest='port', type=int, default=9090,
52
+ help='Server port')
53
+ parser.add_argument(
54
+ '--host', dest='host', type=str, default='0.0.0.0',
55
+ help='Server host')
56
+ parser.add_argument(
57
+ '--kwargs', '--with', dest='kwargs', metavar='KEY=VAL', nargs='+', type=lambda kv: kv.split('='),
58
+ help='Additional LabelStudioMLBase model initialization kwargs')
59
+ parser.add_argument(
60
+ '-d', '--debug', dest='debug', action='store_true',
61
+ help='Switch debug mode')
62
+ parser.add_argument(
63
+ '--log-level', dest='log_level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], default=None,
64
+ help='Logging level')
65
+ parser.add_argument(
66
+ '--model-dir', dest='model_dir', default=os.path.dirname(__file__),
67
+ help='Directory where models are stored (relative to the project directory)')
68
+ parser.add_argument(
69
+ '--check', dest='check', action='store_true',
70
+ help='Validate model instance before launching server')
71
+
72
+ args = parser.parse_args()
73
+
74
+ # setup logging level
75
+ if args.log_level:
76
+ logging.root.setLevel(args.log_level)
77
+
78
+ def isfloat(value):
79
+ try:
80
+ float(value)
81
+ return True
82
+ except ValueError:
83
+ return False
84
+
85
+ def parse_kwargs():
86
+ param = dict()
87
+ for k, v in args.kwargs:
88
+ if v.isdigit():
89
+ param[k] = int(v)
90
+ elif v == 'True' or v == 'true':
91
+ param[k] = True
92
+ elif v == 'False' or v == 'false':
93
+ param[k] = False
94
+ elif isfloat(v):
95
+ param[k] = float(v)
96
+ else:
97
+ param[k] = v
98
+ return param
99
+
100
+ kwargs = get_kwargs_from_config()
101
+
102
+ if args.kwargs:
103
+ kwargs.update(parse_kwargs())
104
+
105
+ if args.check:
106
+ print('Check "' + DINOBackend.__name__ + '" instance creation..')
107
+ model = DINOBackend(**kwargs)
108
+
109
+ app = init_app(model_class=DINOBackend)
110
+
111
+ app.run(host=args.host, port=args.port, debug=args.debug)
112
+
113
+ else:
114
+ # for uWSGI use
115
+ app = init_app(model_class=DINOBackend)
data/ml-backend/models/cache.db ADDED
Binary file (12.3 kB). View file
 
dino.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pathlib
3
+ import logging
4
+ import cv2
5
+ import numpy as np
6
+ import torch
7
+
8
+ from label_studio_sdk.converter import brush
9
+ from typing import List, Dict, Optional
10
+ from uuid import uuid4
11
+ from label_studio_ml.model import LabelStudioMLBase, ModelResponse
12
+ from label_studio_sdk._extensions.label_studio_tools.core.utils.params import get_bool_env
13
+ from label_studio_sdk.label_interface.objects import PredictionValue
14
+ from segment_anything.utils.transforms import ResizeLongestSide
15
+
16
+ from groundingdino.util.inference import load_model, load_image, predict, annotate
17
+ from groundingdino.util import box_ops
18
+
19
+ # ----Extra Libraries
20
+
21
+ from typing import Tuple, List
22
+
23
+ from groundingdino.util.utils import get_phrases_from_posmap
24
+ from groundingdino.util.inference import preprocess_caption
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def predict_batch(
30
+ model,
31
+ images: torch.Tensor,
32
+ caption: str,
33
+ box_threshold: float,
34
+ text_threshold: float,
35
+ device: str = "cuda"
36
+ ) -> Tuple[List[torch.Tensor], List[torch.Tensor], List[List[str]]]:
37
+ # copy from https://github.com/yuwenmichael/Grounding-DINO-Batch-Inference/blob/main/batch_utlities.py
38
+ '''
39
+ return:
40
+ bboxes_batch: list of tensors of shape (n, 4)
41
+ predicts_batch: list of tensors of shape (n,)
42
+ phrases_batch: list of list of strings of shape (n,)
43
+ n is the number of boxes in one image
44
+ '''
45
+ caption = preprocess_caption(caption=caption)
46
+ model = model.to(device)
47
+ image = images.to(device)
48
+ with torch.no_grad():
49
+ outputs = model(image, captions=[caption for _ in range(
50
+ len(images))]) # <------- I use the same caption for all the images for my use-case
51
+ prediction_logits = outputs["pred_logits"].cpu().sigmoid() # prediction_logits.shape = (num_batch, nq, 256)
52
+ prediction_boxes = outputs["pred_boxes"].cpu() # prediction_boxes.shape = (num_batch, nq, 4)
53
+
54
+ mask = prediction_logits.max(dim=2)[0] > box_threshold # mask: torch.Size([num_batch, 256])
55
+
56
+ bboxes_batch = []
57
+ predicts_batch = []
58
+ phrases_batch = [] # list of lists
59
+ tokenizer = model.tokenizer
60
+ tokenized = tokenizer(caption)
61
+ for i in range(prediction_logits.shape[0]):
62
+ logits = prediction_logits[i][mask[i]] # logits.shape = (n, 256)
63
+ phrases = [
64
+ get_phrases_from_posmap(logit > text_threshold, tokenized, tokenizer).replace('.', '')
65
+ for logit # logit is a tensor of shape (256,) torch.Size([256])
66
+ in logits # torch.Size([7, 256])
67
+ ]
68
+ boxes = prediction_boxes[i][mask[i]] # boxes.shape = (n, 4)
69
+ phrases_batch.append(phrases)
70
+ bboxes_batch.append(boxes)
71
+ predicts_batch.append(logits.max(dim=1)[0])
72
+
73
+ return bboxes_batch, predicts_batch, phrases_batch
74
+
75
+
76
+ # LOADING THE MODEL
77
+ groundingdino_model = load_model(
78
+ pathlib.Path(os.environ.get('GROUNDINGDINO_REPO_PATH', "./GroundingDINO")) / "groundingdino" / "config" / "GroundingDINO_SwinT_OGC.py",
79
+ pathlib.Path(os.environ.get('GROUNDINGDINO_REPO_PATH', "./GroundingDINO")) / "weights" / "groundingdino_swint_ogc.pth"
80
+ )
81
+
82
+
83
+ BOX_THRESHOLD = os.environ.get("BOX_THRESHOLD", 0.3)
84
+ TEXT_THRESHOLD = os.environ.get("TEXT_THRESHOLD", 0.25)
85
+ LABEL_STUDIO_ACCESS_TOKEN = (
86
+ os.environ.get("LABEL_STUDIO_ACCESS_TOKEN") or os.environ.get("LABEL_STUDIO_API_KEY")
87
+ )
88
+ LABEL_STUDIO_HOST = (
89
+ os.environ.get("LABEL_STUDIO_HOST") or os.environ.get("LABEL_STUDIO_URL")
90
+ )
91
+
92
+ USE_SAM = get_bool_env("USE_SAM", default=False)
93
+ USE_MOBILE_SAM = get_bool_env("USE_MOBILE_SAM", default=False)
94
+
95
+ MOBILESAM_CHECKPOINT = os.environ.get("MOBILESAM_CHECKPOINT", "mobile_sam.pt")
96
+ SAM_CHECKPOINT = os.environ.get("SAM_CHECKPOINT", "sam_vit_h_4b8939.pth")
97
+
98
+
99
+ device = "cuda" if torch.cuda.is_available() else "cpu"
100
+ logger.info(f"Using device {device}")
101
+
102
+
103
+ if USE_MOBILE_SAM:
104
+ logger.info(f"Using Mobile-SAM with checkpoint {MOBILESAM_CHECKPOINT}")
105
+ from mobile_sam import SamPredictor, sam_model_registry
106
+
107
+ model_checkpoint = MOBILESAM_CHECKPOINT
108
+ reg_key = 'vit_t'
109
+ elif USE_SAM:
110
+ logger.info(f"Using SAM with checkpoint {SAM_CHECKPOINT}")
111
+ from segment_anything import SamPredictor, sam_model_registry
112
+
113
+ model_checkpoint = SAM_CHECKPOINT
114
+ reg_key = 'vit_h'
115
+ else:
116
+ reg_key = None
117
+ model_checkpoint = None
118
+ logger.info("Using GroundingDINO without SAM")
119
+
120
+ if USE_MOBILE_SAM or USE_SAM:
121
+ logger.info(f"Loading SAM model with checkpoint {model_checkpoint}")
122
+ sam = sam_model_registry[reg_key](checkpoint=model_checkpoint)
123
+ sam.to(device=device)
124
+ predictor = SamPredictor(sam)
125
+ logger.info("SAM model successfully loaded!")
126
+
127
+
128
+ class DINOBackend(LabelStudioMLBase):
129
+
130
+ def setup(self):
131
+ self.set("model_version", f'{self.__class__.__name__}-v0.0.1')
132
+
133
+ def predict(self, tasks: List[Dict], context: Optional[Dict] = None, **kwargs) -> List[Dict]:
134
+
135
+ if not context or not context.get('result'):
136
+ # if there is no context, no interaction has happened yet
137
+ return []
138
+
139
+ from_name_r, to_name_r, value = self.get_first_tag_occurence('RectangleLabels', 'Image')
140
+ from_name_b, to_name_b, _ = self.get_first_tag_occurence('BrushLabels', 'Image')
141
+
142
+ text_prompt = context['result'][0]['value']['text'][0]
143
+ logger.debug(f"Prompt: {text_prompt}")
144
+
145
+ logger.info(f"the prompt is {text_prompt} and {from_name_r} and {from_name_b}")
146
+
147
+ final_predictions = []
148
+ if len(tasks) > 1:
149
+ logger.info(f"Running multiple tasks with {len(tasks)} images")
150
+ final_predictions = self.multiple_tasks(
151
+ tasks, text_prompt, from_name_r, to_name_r, from_name_b, to_name_b, value)
152
+ elif len(tasks) == 1:
153
+ logger.info(f"Running single task {tasks[0]}")
154
+ final_predictions = self.one_task(
155
+ tasks[0], text_prompt, from_name_r, to_name_r, from_name_b, to_name_b, value)
156
+ return final_predictions
157
+
158
+ def one_task(self, task, prompt, from_name_r, to_name_r, from_name_b, to_name_b, value):
159
+ all_points = []
160
+ all_scores = []
161
+ all_lengths = []
162
+ predictions = []
163
+ raw_img_path = task['data'][value]
164
+
165
+ try:
166
+ img_path = self.get_local_path(
167
+ raw_img_path,
168
+ ls_access_token=LABEL_STUDIO_ACCESS_TOKEN,
169
+ ls_host=LABEL_STUDIO_HOST,
170
+ task_id=task.get('id')
171
+ )
172
+ except Exception as e:
173
+ logger.error(f"Error getting image path: {e}")
174
+ img_path = raw_img_path
175
+
176
+ src, img = load_image(img_path)
177
+
178
+ boxes, logits, _ = predict(
179
+ model=groundingdino_model,
180
+ image=img,
181
+ caption=prompt,
182
+ box_threshold=float(BOX_THRESHOLD),
183
+ text_threshold=float(TEXT_THRESHOLD),
184
+ device=device
185
+ )
186
+
187
+ H, W, _ = src.shape
188
+
189
+ boxes_xyxy = box_ops.box_cxcywh_to_xyxy(boxes) * torch.Tensor([W, H, W, H])
190
+
191
+ points = boxes_xyxy.cpu().numpy()
192
+
193
+ for point, logit in zip(points, logits):
194
+ all_points.append(point)
195
+ all_scores.append(logit)
196
+ all_lengths.append((H, W))
197
+
198
+ if USE_MOBILE_SAM or USE_SAM:
199
+ # get <BrushLabels> results
200
+ predictions.append(self.get_sam_results(img_path, all_points, all_lengths, from_name_b, to_name_b))
201
+ else:
202
+ # get <RectangleLabels> results
203
+ predictions.append(self.get_results(all_points, all_scores, all_lengths, from_name_r, to_name_r))
204
+
205
+ return predictions
206
+
207
+ def multiple_tasks(self, tasks, prompt, from_name_r, to_name_r, from_name_b, to_name_b, value):
208
+
209
+ # first getting all the image paths
210
+ image_paths = []
211
+
212
+ for task in tasks:
213
+ raw_img_path = task['data'][value]
214
+
215
+ try:
216
+ img_path = self.get_local_path(
217
+ raw_img_path,
218
+ ls_access_token=LABEL_STUDIO_ACCESS_TOKEN,
219
+ ls_host=LABEL_STUDIO_HOST,
220
+ task_id=task.get('id')
221
+ )
222
+ except Exception as e:
223
+ logger.error(f"Error getting local path: {e}")
224
+ img_path = raw_img_path
225
+
226
+ image_paths.append(img_path)
227
+
228
+ boxes, logits, lengths = self.batch_dino(image_paths, prompt)
229
+
230
+ box_by_task = []
231
+ for (box_task, (H, W)) in zip(boxes, lengths):
232
+
233
+ boxes_xyxy = box_ops.box_cxcywh_to_xyxy(box_task) * torch.Tensor([W, H, W, H])
234
+
235
+ box_by_task.append(boxes_xyxy)
236
+
237
+ if USE_MOBILE_SAM or USE_SAM:
238
+ batched_output = self.batch_sam(input_boxes_list=box_by_task, image_paths=image_paths)
239
+ predictions = self.get_batched_sam_results(batched_output, from_name_b, to_name_b)
240
+
241
+ else:
242
+ predictions = []
243
+
244
+ for boxes_xyxy, (H, W), logits in zip(box_by_task, lengths, logits):
245
+ points = boxes_xyxy.cpu().numpy()
246
+
247
+ all_points = []
248
+ all_scores = []
249
+ all_lengths = []
250
+
251
+ for point, logit in zip(points, logits):
252
+ all_points.append(point)
253
+ all_scores.append(logit)
254
+ all_lengths.append((H, W)) # figure out how to get this
255
+
256
+ predictions.append(self.get_results(all_points, all_scores, all_lengths, from_name_r, to_name_r))
257
+
258
+ return predictions
259
+
260
+ # make sure you use new github repo when predicting in batch
261
+ def batch_dino(self, image_paths, prompt):
262
+ # text prompt is same as self.label
263
+ loaded_images = []
264
+ lengths = []
265
+ for img in image_paths:
266
+ src, img = load_image(img)
267
+ loaded_images.append(img)
268
+
269
+ H, W, _ = src.shape
270
+
271
+ lengths.append((H, W))
272
+
273
+ images = torch.stack(loaded_images)
274
+
275
+ if len(image_paths) <= 3:
276
+ boxes, logits, _ = predict_batch(
277
+ model=groundingdino_model,
278
+ images=images,
279
+ caption=prompt, # text prompt is same as self.label
280
+ box_threshold=float(BOX_THRESHOLD),
281
+ text_threshold=float(TEXT_THRESHOLD),
282
+ device=device
283
+ )
284
+
285
+ else:
286
+ all_boxes = []
287
+ all_logits = []
288
+ for img in loaded_images:
289
+ boxes, logits, _ = predict(
290
+ model=groundingdino_model,
291
+ image=img,
292
+ caption=prompt,
293
+ box_threshold=float(BOX_THRESHOLD),
294
+ text_threshold=float(TEXT_THRESHOLD),
295
+ device=device
296
+ )
297
+ all_boxes.append(boxes)
298
+ all_logits.append(logits)
299
+
300
+ boxes = all_boxes
301
+ logits = all_logits
302
+
303
+ return boxes, logits, lengths
304
+
305
+ def batch_sam(self, input_boxes_list, image_paths):
306
+
307
+ resize_transform = ResizeLongestSide(sam.image_encoder.img_size)
308
+
309
+ # from SAM code base
310
+ def prepare_image(image, transform, device):
311
+ image = transform.apply_image(image)
312
+ image = torch.as_tensor(image, device=device.device)
313
+ return image.permute(2, 0, 1).contiguous()
314
+
315
+ batched_input = []
316
+ for input_box, path in zip(input_boxes_list, image_paths):
317
+ image = cv2.imread(path)
318
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
319
+ batched_input.append({
320
+ 'image': prepare_image(image, resize_transform, sam),
321
+ 'boxes': resize_transform.apply_boxes_torch(input_box, image.shape[:2]),
322
+ 'original_size': image.shape[:2]
323
+ })
324
+
325
+ batched_output = sam(batched_input, multimask_output=False)
326
+
327
+ return batched_output
328
+
329
+ def get_batched_sam_results(self, batched_output, from_name_b, to_name_b):
330
+
331
+ predictions = []
332
+
333
+ for output in batched_output:
334
+ masks = output['masks']
335
+ masks = masks[:, 0, :, :].cpu().numpy().astype(np.uint8)
336
+
337
+ probs = output['iou_predictions'].cpu().numpy()
338
+
339
+ num_masks = masks.shape[0]
340
+ height = masks.shape[-2]
341
+ width = masks.shape[-1]
342
+
343
+ lengths = [(height, width)] * num_masks
344
+
345
+ predictions.append(self.sam_predictions(masks, probs, lengths, from_name_b, to_name_b))
346
+
347
+ return predictions
348
+
349
+ def get_results(self, all_points, all_scores, all_lengths, from_name_r, to_name_r):
350
+
351
+ results = []
352
+ total_score = 0
353
+ for points, scores, lengths in zip(all_points, all_scores, all_lengths):
354
+ # random ID
355
+ label_id = str(uuid4())[:9]
356
+
357
+ height, width = lengths
358
+ score = scores.item()
359
+ total_score += score
360
+
361
+ results.append({
362
+ 'id': label_id,
363
+ 'from_name': from_name_r,
364
+ 'to_name': to_name_r,
365
+ 'original_width': width,
366
+ 'original_height': height,
367
+ 'image_rotation': 0,
368
+ 'value': {
369
+ 'rotation': 0,
370
+ 'width': (points[2] - points[0]) / width * 100,
371
+ 'height': (points[3] - points[1]) / height * 100,
372
+ 'x': points[0] / width * 100,
373
+ 'y': points[1] / height * 100
374
+ },
375
+ 'score': score,
376
+ 'type': 'rectanglelabels',
377
+ 'readonly': False
378
+ })
379
+
380
+ total_score /= max(len(results), 1)
381
+
382
+ return {
383
+ 'result': results,
384
+ 'score': total_score,
385
+ 'model_version': self.get('model_version')
386
+ }
387
+
388
+ def get_sam_results(
389
+ self,
390
+ img_path,
391
+ input_boxes,
392
+ lengths,
393
+ from_name_b,
394
+ to_name_b
395
+ ):
396
+ image = cv2.imread(img_path)
397
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
398
+ predictor.set_image(image)
399
+
400
+ input_boxes = torch.from_numpy(np.array(input_boxes))
401
+
402
+ transformed_boxes = predictor.transform.apply_boxes_torch(input_boxes, image.shape[:2]).to(device)
403
+ masks, probs, _ = predictor.predict_torch(
404
+ point_coords=None,
405
+ point_labels=None,
406
+ boxes=transformed_boxes,
407
+ multimask_output=False,
408
+ )
409
+
410
+ masks = masks[:, 0, :, :].cpu().numpy().astype(np.uint8)
411
+ probs = probs.cpu().numpy()
412
+
413
+ return self.sam_predictions(masks, probs, lengths, from_name_b, to_name_b)
414
+
415
+ # takes straight masks and returns predictions
416
+ def sam_predictions(self, masks, probs, lengths, from_name_b, to_name_b):
417
+
418
+ results = []
419
+ total_score = 0
420
+ for mask, prob, length in zip(masks, probs, lengths):
421
+ height, width = length
422
+ # creates a random ID for your label everytime so no chance for errors
423
+ label_id = str(uuid4())[:9]
424
+
425
+ # converting the mask from the model to RLE format which is usable in Label Studio
426
+ mask = mask * 255
427
+ rle = brush.mask2rle(mask)
428
+ score = float(prob[0])
429
+
430
+ results.append({
431
+ 'id': label_id,
432
+ 'from_name': from_name_b,
433
+ 'to_name': to_name_b,
434
+ 'original_width': width,
435
+ 'original_height': height,
436
+ 'image_rotation': 0,
437
+ 'value': {
438
+ 'format': 'rle',
439
+ 'rle': rle
440
+ },
441
+ 'score': score,
442
+ 'type': 'brushlabels',
443
+ 'readonly': False
444
+ })
445
+ total_score += score
446
+ return {
447
+ 'result': results,
448
+ 'score': total_score / max(len(results), 1),
449
+ 'model_version': self.get('model_version')
450
+ }
docker-compose.yml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: "3.11"
2
+
3
+ services:
4
+ grounding_sam:
5
+ container_name: grounding_sam
6
+ image: heartexlabs/label-studio-ml-backend:grounding_sam-master
7
+ build:
8
+ context: .
9
+ args:
10
+ TEST_ENV: ${TEST_ENV}
11
+ # Increase the memory limit if you USE_SAM=true on CPU machine
12
+ # deploy:
13
+ # resources:
14
+ # reservations:
15
+ # memory: 16G
16
+ environment:
17
+ - MODEL_DIR=/data/models
18
+ - WORKERS=2
19
+ - THREADS=4
20
+ - LOG_LEVEL=DEBUG
21
+
22
+ # Add these variables if you want to access the images stored in Label Studio
23
+ - LABEL_STUDIO_HOST=
24
+ - LABEL_STUDIO_ACCESS_TOKEN=
25
+
26
+ # use these if you want to use segment anything instead of bounding box predictions from input text prompts
27
+ - USE_SAM=false # if you want to automatically generate segment anything model predictions
28
+ - USE_MOBILE_SAM=false # whether you want to use a more efficient, yet a bit less accurate, version of the segment anything model
29
+
30
+ - BOX_THRESHOLD=0.30
31
+ - TEXT_THRESHOLD=0.25
32
+ # # Uncomment the following lines if you want to use GPU
33
+ # - NVIDIA_VISIBLE_DEVICES=all
34
+ # deploy:
35
+ # resources:
36
+ # reservations:
37
+ # devices:
38
+ # - driver: nvidia
39
+ # count: 1
40
+ # capabilities: [gpu]
41
+ ports:
42
+ - "9090:9090"
43
+ volumes:
44
+ - "./data/ml-backend:/data"
45
+ - "./prompt.txt:/app/prompt.txt"
46
+ - ./dino.py:/app/dino.py
requirements-test.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ pytest
2
+ pytest-cov
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ gunicorn==22.0.0
2
+ label-studio-ml @ git+https://github.com/HumanSignal/label-studio-ml-backend.git@master
3
+ mobile-sam @ git+https://github.com/ChaoningZhang/MobileSAM.git
4
+ # torch -- inherited from GroundingDINO repo
5
+ # torchvision -- inherited from GroundingDINO repo
6
+ # opencv-python -- inherited from GroundingDINO repo
7
+ segment-anything==1.0
8
+ olefile==0.47
9
+ # networkx==2.8.8
start.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Execute the gunicorn command
4
+ exec gunicorn --bind :${PORT:-9090} --workers ${WORKERS:-1} --threads ${THREADS:-4} --timeout 0 _wsgi:app
test_api.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import pytest
2
+
3
+
4
+ def test_example():
5
+ assert True