ashhadahsan commited on
Commit
8e5dadf
·
verified ·
1 Parent(s): 47b0ecc

Upload 21 files

Browse files
.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
+ assets/outputs/car.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/outputs/fruits.png filter=lfs diff=lfs merge=lfs -text
38
+ assets/outputs/person.png filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04
2
+
3
+ # Set environment variables
4
+ ENV DEBIAN_FRONTEND=noninteractive
5
+ ENV GRADIO_SERVER_NAME="0.0.0.0"
6
+
7
+ # Install necessary packages
8
+ RUN apt-get update && apt-get install -y \
9
+ python3 \
10
+ python3-pip \
11
+ openssh-client \
12
+ build-essential \
13
+ git
14
+
15
+ COPY . /lang-segment-anything
16
+
17
+ # Install dependencies
18
+ WORKDIR /lang-segment-anything
19
+ RUN pip install -r requirements.txt
20
+
21
+ EXPOSE 8000
22
+
23
+ # Entry point
24
+ CMD ["python3", "app.py"]
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,12 +1,98 @@
1
- ---
2
- title: Lang Segment Anything Gradio
3
- emoji: 📚
4
- colorFrom: pink
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 5.7.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Language Segment-Anything
2
+
3
+ Language Segment-Anything is an open-source project that combines the power of instance segmentation and text prompts to generate masks for specific objects in images. Built on the recently released Meta model, Segment Anything Model 2, and the GroundingDINO detection model, it's an easy-to-use and effective tool for object detection and image segmentation.
4
+
5
+ ![person.png](/assets/outputs/person.png)
6
+
7
+ ## Features
8
+
9
+ - Zero-shot text-to-bbox approach for object detection.
10
+ - GroundingDINO detection model integration.
11
+ - SAM 2.1
12
+ - Batch inference support.
13
+ - Easy endpoint deployment using the Lightning AI litserve platform.
14
+ - Customizable text prompts for precise object segmentation.
15
+
16
+ ## Getting Started
17
+
18
+ ### Prerequisites
19
+
20
+ - Python 3.11 or higher
21
+
22
+ ### Installation
23
+
24
+ #### Installing PyTorch Dependencies
25
+
26
+ Before installing `lang-sam`, please install PyTorch using the following command:
27
+
28
+ ```bash
29
+
30
+ pip install torch==2.4.1 torchvision==0.19.1 --extra-index-url https://download.pytorch.org/whl/cu124
31
+
32
+ ```
33
+
34
+ ```bash
35
+
36
+ pip install -U git+https://github.com/luca-medeiros/lang-segment-anything.git
37
+
38
+ ```
39
+
40
+ Or
41
+ Clone the repository and install the required packages:
42
+
43
+ ```bash
44
+
45
+ git clone https://github.com/luca-medeiros/lang-segment-anything && cd lang-segment-anything
46
+ pip install -e .
47
+
48
+ ```
49
+
50
+ #### Docker Installation
51
+
52
+ Build and run the image.
53
+
54
+ ```bash
55
+
56
+ git clone https://github.com/luca-medeiros/lang-segment-anything && cd lang-segment-anything
57
+ docker build --tag lang-segment-anything:latest .
58
+ docker run --gpus all -p 8000:8000 lang-segment-anything:latest
59
+
60
+ ```
61
+
62
+ ### Usage
63
+
64
+ To run the gradio APP:
65
+
66
+ `python app.py`
67
+ And open `http://0.0.0.0:8000/gradio`
68
+
69
+ Use as a library:
70
+
71
+ ```python
72
+ from PIL import Image
73
+ from lang_sam import LangSAM
74
+
75
+ model = LangSAM()
76
+ image_pil = Image.open("./assets/car.jpeg").convert("RGB")
77
+ text_prompt = "wheel."
78
+ results = model.predict([image_pil], [text_prompt])
79
+ ```
80
+
81
+ ## Examples
82
+
83
+ ![car.png](/assets/outputs/car.png)
84
+
85
+ ![fruits.png](/assets/outputs/fruits.png)
86
+
87
+ ## Acknowledgments
88
+
89
+ This project is based on/used the following repositories:
90
+
91
+ - [GroundingDINO](https://github.com/IDEA-Research/GroundingDINO)
92
+ - [Segment-Anything](https://github.com/facebookresearch/segment-anything-2)
93
+ - [LitServe](https://github.com/Lightning-AI/LitServe/)
94
+ - [Supervision](https://github.com/roboflow/supervision)
95
+
96
+ ## License
97
+
98
+ This project is licensed under the Apache 2.0 License
app.py CHANGED
@@ -1,7 +1,98 @@
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
1
+ import os
2
+ from io import BytesIO
3
+
4
  import gradio as gr
5
+ import requests
6
+ from PIL import Image
7
+
8
+ from lang_sam import SAM_MODELS
9
+ from lang_sam.server import PORT, server
10
+
11
+
12
+ def inference(sam_type, box_threshold, text_threshold, image, text_prompt):
13
+ """Gradio function that makes a request to the /predict LitServe endpoint."""
14
+ url = f"http://localhost:{PORT}/predict" # Adjust port if needed
15
+
16
+ # Prepare the multipart form data
17
+ with open(image, "rb") as img_file:
18
+ files = {
19
+ "image": img_file,
20
+ }
21
+ data = {
22
+ "sam_type": sam_type,
23
+ "box_threshold": str(box_threshold),
24
+ "text_threshold": str(text_threshold),
25
+ "text_prompt": text_prompt,
26
+ }
27
+
28
+ try:
29
+ response = requests.post(url, files=files, data=data)
30
+ except Exception as e:
31
+ print(f"Request failed: {e}")
32
+ return None
33
+
34
+ if response.status_code == 200:
35
+ try:
36
+ output_image = Image.open(BytesIO(response.content)).convert("RGB")
37
+ return output_image
38
+ except Exception as e:
39
+ print(f"Failed to process response image: {e}")
40
+ return None
41
+ else:
42
+ print(f"Request failed with status code {response.status_code}: {response.text}")
43
+ return None
44
+
45
+
46
+ with gr.Blocks(title="lang-sam") as blocks:
47
+ with gr.Row():
48
+ sam_model_choices = gr.Dropdown(choices=list(SAM_MODELS.keys()), label="SAM Model", value="sam2.1_hiera_small")
49
+ box_threshold = gr.Slider(minimum=0.0, maximum=1.0, value=0.3, label="Box Threshold")
50
+ text_threshold = gr.Slider(minimum=0.0, maximum=1.0, value=0.25, label="Text Threshold")
51
+ with gr.Row():
52
+ image_input = gr.Image(type="filepath", label="Input Image")
53
+ output_image = gr.Image(type="pil", label="Output Image")
54
+ text_prompt = gr.Textbox(lines=1, label="Text Prompt")
55
+
56
+ submit_btn = gr.Button("Run Prediction")
57
+
58
+ submit_btn.click(
59
+ fn=inference,
60
+ inputs=[sam_model_choices, box_threshold, text_threshold, image_input, text_prompt],
61
+ outputs=output_image,
62
+ )
63
+
64
+ examples = [
65
+ [
66
+ "sam2.1_hiera_small",
67
+ 0.32,
68
+ 0.25,
69
+ os.path.join(os.path.dirname(__file__), "assets", "fruits.jpg"),
70
+ "kiwi. watermelon. blueberry.",
71
+ ],
72
+ [
73
+ "sam2.1_hiera_small",
74
+ 0.3,
75
+ 0.25,
76
+ os.path.join(os.path.dirname(__file__), "assets", "car.jpeg"),
77
+ "wheel.",
78
+ ],
79
+ [
80
+ "sam2.1_hiera_small",
81
+ 0.3,
82
+ 0.25,
83
+ os.path.join(os.path.dirname(__file__), "assets", "food.jpg"),
84
+ "food.",
85
+ ],
86
+ ]
87
+
88
+ gr.Examples(
89
+ examples=examples,
90
+ inputs=[sam_model_choices, box_threshold, text_threshold, image_input, text_prompt],
91
+ outputs=output_image,
92
+ )
93
 
94
+ server.app = gr.mount_gradio_app(server.app, blocks, path="/gradio")
 
95
 
96
+ if __name__ == "__main__":
97
+ print(f"Starting LitServe and Gradio server on port {PORT}...")
98
+ server.run(port=PORT)
assets/car.jpeg ADDED
assets/food.jpg ADDED
assets/fruits.jpg ADDED
assets/outputs/car.png ADDED

Git LFS Details

  • SHA256: 988188ac26215f9cd6631b98e8faf01715b89e616c7c00f1e59c078532e466f0
  • Pointer size: 132 Bytes
  • Size of remote file: 4.34 MB
assets/outputs/fruits.png ADDED

Git LFS Details

  • SHA256: 5577c7d3ec2ec07c1f72fbce91726582d9c1a38311d0e939f709890c6076649e
  • Pointer size: 132 Bytes
  • Size of remote file: 3.52 MB
assets/outputs/person.png ADDED

Git LFS Details

  • SHA256: 224492c6a763f5f248ff7f92701b40e0020ee3da34a46557f15c63e30b798d73
  • Pointer size: 132 Bytes
  • Size of remote file: 6.81 MB
assets/person.jpg ADDED
lang_sam/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from lang_sam.lang_sam import LangSAM
2
+ from lang_sam.models.sam import SAM_MODELS
lang_sam/lang_sam.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from PIL import Image
3
+
4
+ from lang_sam.models.gdino import GDINO
5
+ from lang_sam.models.sam import SAM
6
+
7
+
8
+ class LangSAM:
9
+ def __init__(self, sam_type="sam2.1_hiera_small", ckpt_path: str | None = None):
10
+ self.sam_type = sam_type
11
+ self.sam = SAM()
12
+ self.sam.build_model(sam_type, ckpt_path)
13
+ self.gdino = GDINO()
14
+ self.gdino.build_model()
15
+
16
+ def predict(
17
+ self,
18
+ images_pil: list[Image.Image],
19
+ texts_prompt: list[str],
20
+ box_threshold: float = 0.3,
21
+ text_threshold: float = 0.25,
22
+ ):
23
+ """Predicts masks for given images and text prompts using GDINO and SAM models.
24
+
25
+ Parameters:
26
+ images_pil (list[Image.Image]): List of input images.
27
+ texts_prompt (list[str]): List of text prompts corresponding to the images.
28
+ box_threshold (float): Threshold for box predictions.
29
+ text_threshold (float): Threshold for text predictions.
30
+
31
+ Returns:
32
+ list[dict]: List of results containing masks and other outputs for each image.
33
+ Output format:
34
+ [{
35
+ "boxes": np.ndarray,
36
+ "scores": np.ndarray,
37
+ "masks": np.ndarray,
38
+ "mask_scores": np.ndarray,
39
+ }, ...]
40
+ """
41
+
42
+ gdino_results = self.gdino.predict(images_pil, texts_prompt, box_threshold, text_threshold)
43
+ all_results = []
44
+ sam_images = []
45
+ sam_boxes = []
46
+ sam_indices = []
47
+ for idx, result in enumerate(gdino_results):
48
+ processed_result = {
49
+ **result,
50
+ "masks": [],
51
+ "mask_scores": [],
52
+ }
53
+
54
+ if result["labels"]:
55
+ processed_result["boxes"] = result["boxes"].cpu().numpy()
56
+ processed_result["scores"] = result["scores"].cpu().numpy()
57
+ sam_images.append(np.asarray(images_pil[idx]))
58
+ sam_boxes.append(processed_result["boxes"])
59
+ sam_indices.append(idx)
60
+
61
+ all_results.append(processed_result)
62
+ if sam_images:
63
+ print(f"Predicting {len(sam_boxes)} masks")
64
+ masks, mask_scores, _ = self.sam.predict_batch(sam_images, xyxy=sam_boxes)
65
+ for idx, mask, score in zip(sam_indices, masks, mask_scores):
66
+ all_results[idx].update(
67
+ {
68
+ "masks": mask,
69
+ "mask_scores": score,
70
+ }
71
+ )
72
+ print(f"Predicted {len(all_results)} masks")
73
+ return all_results
74
+
75
+
76
+ if __name__ == "__main__":
77
+ model = LangSAM()
78
+ out = model.predict(
79
+ [Image.open("./assets/food.jpg"), Image.open("./assets/car.jpeg")],
80
+ ["food", "car"],
81
+ )
82
+ print(out)
lang_sam/models/__init__.py ADDED
File without changes
lang_sam/models/gdino.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor
4
+
5
+ from lang_sam.models.utils import get_device_type
6
+
7
+ device_type = get_device_type()
8
+ DEVICE = torch.device(device_type)
9
+
10
+ if torch.cuda.is_available():
11
+ torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
12
+ if torch.cuda.get_device_properties(0).major >= 8:
13
+ torch.backends.cuda.matmul.allow_tf32 = True
14
+ torch.backends.cudnn.allow_tf32 = True
15
+
16
+
17
+ class GDINO:
18
+ def __init__(self):
19
+ self.build_model()
20
+
21
+ def build_model(self, ckpt_path: str | None = None):
22
+ model_id = "IDEA-Research/grounding-dino-base"
23
+ self.processor = AutoProcessor.from_pretrained(model_id)
24
+ self.model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id).to(
25
+ DEVICE
26
+ )
27
+
28
+ def predict(
29
+ self,
30
+ pil_images: list[Image.Image],
31
+ text_prompt: list[str],
32
+ box_threshold: float,
33
+ text_threshold: float,
34
+ ) -> list[dict]:
35
+ for i, prompt in enumerate(text_prompt):
36
+ if prompt[-1] != ".":
37
+ text_prompt[i] += "."
38
+ inputs = self.processor(images=pil_images, text=text_prompt, return_tensors="pt").to(DEVICE)
39
+ with torch.no_grad():
40
+ outputs = self.model(**inputs)
41
+
42
+ results = self.processor.post_process_grounded_object_detection(
43
+ outputs,
44
+ inputs.input_ids,
45
+ box_threshold=box_threshold,
46
+ text_threshold=text_threshold,
47
+ target_sizes=[k.size[::-1] for k in pil_images],
48
+ )
49
+ return results
50
+
51
+
52
+ if __name__ == "__main__":
53
+ gdino = GDINO()
54
+ gdino.build_model()
55
+ out = gdino.predict(
56
+ [Image.open("./assets/car.jpeg"), Image.open("./assets/car.jpeg")],
57
+ ["wheel", "wheel"],
58
+ 0.3,
59
+ 0.25,
60
+ )
61
+ print(out)
lang_sam/models/sam.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from hydra import compose
4
+ from hydra.utils import instantiate
5
+ from omegaconf import OmegaConf
6
+ from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator
7
+ from sam2.sam2_image_predictor import SAM2ImagePredictor
8
+
9
+ from lang_sam.models.utils import get_device_type
10
+
11
+ DEVICE = torch.device(get_device_type())
12
+
13
+ if torch.cuda.is_available():
14
+ torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
15
+ if torch.cuda.get_device_properties(0).major >= 8:
16
+ torch.backends.cuda.matmul.allow_tf32 = True
17
+ torch.backends.cudnn.allow_tf32 = True
18
+
19
+
20
+ SAM_MODELS = {
21
+ "sam2.1_hiera_tiny": {
22
+ "url": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_tiny.pt",
23
+ "config": "configs/sam2.1/sam2.1_hiera_t.yaml",
24
+ },
25
+ "sam2.1_hiera_small": {
26
+ "url": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_small.pt",
27
+ "config": "configs/sam2.1/sam2.1_hiera_s.yaml",
28
+ },
29
+ "sam2.1_hiera_base_plus": {
30
+ "url": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_base_plus.pt",
31
+ "config": "configs/sam2.1/sam2.1_hiera_b+.yaml",
32
+ },
33
+ "sam2.1_hiera_large": {
34
+ "url": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_large.pt",
35
+ "config": "configs/sam2.1/sam2.1_hiera_l.yaml",
36
+ },
37
+ }
38
+
39
+
40
+ class SAM:
41
+ def build_model(self, sam_type: str, ckpt_path: str | None = None):
42
+ self.sam_type = sam_type
43
+ self.ckpt_path = ckpt_path
44
+ cfg = compose(config_name=SAM_MODELS[self.sam_type]["config"], overrides=[])
45
+ OmegaConf.resolve(cfg)
46
+ self.model = instantiate(cfg.model, _recursive_=True)
47
+ self._load_checkpoint(self.model)
48
+ self.model = self.model.to(DEVICE)
49
+ self.model.eval()
50
+ self.mask_generator = SAM2AutomaticMaskGenerator(self.model)
51
+ self.predictor = SAM2ImagePredictor(self.model)
52
+
53
+ def _load_checkpoint(self, model: torch.nn.Module):
54
+ if self.ckpt_path is None:
55
+ checkpoint_url = SAM_MODELS[self.sam_type]["url"]
56
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")["model"]
57
+ else:
58
+ state_dict = torch.load(self.ckpt_path, map_location="cpu", weights_only=True)
59
+ try:
60
+ model.load_state_dict(state_dict, strict=True)
61
+ except Exception as e:
62
+ raise ValueError(f"Problem loading SAM please make sure you have the right model type: {self.sam_type} \
63
+ and a working checkpoint: {checkpoint_url}. Recommend deleting the checkpoint and \
64
+ re-downloading it. Error: {e}")
65
+
66
+ def generate(self, image_rgb: np.ndarray) -> list[dict]:
67
+ """
68
+ Output format
69
+ SAM2AutomaticMaskGenerator returns a list of masks, where each mask is a dict containing various information
70
+ about the mask:
71
+
72
+ segmentation - [np.ndarray] - the mask with (W, H) shape, and bool type
73
+ area - [int] - the area of the mask in pixels
74
+ bbox - [List[int]] - the boundary box of the mask in xywh format
75
+ predicted_iou - [float] - the model's own prediction for the quality of the mask
76
+ point_coords - [List[List[float]]] - the sampled input point that generated this mask
77
+ stability_score - [float] - an additional measure of mask quality
78
+ crop_box - List[int] - the crop of the image used to generate this mask in xywh format
79
+ """
80
+
81
+ sam2_result = self.mask_generator.generate(image_rgb)
82
+ return sam2_result
83
+
84
+ def predict(self, image_rgb: np.ndarray, xyxy: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
85
+ self.predictor.set_image(image_rgb)
86
+ masks, scores, logits = self.predictor.predict(box=xyxy, multimask_output=False)
87
+ if len(masks.shape) > 3:
88
+ masks = np.squeeze(masks, axis=1)
89
+ return masks, scores, logits
90
+
91
+ def predict_batch(
92
+ self,
93
+ images_rgb: list[np.ndarray],
94
+ xyxy: list[np.ndarray],
95
+ ) -> tuple[list[np.ndarray], list[np.ndarray], list[np.ndarray]]:
96
+ self.predictor.set_image_batch(images_rgb)
97
+
98
+ masks, scores, logits = self.predictor.predict_batch(box_batch=xyxy, multimask_output=False)
99
+
100
+ masks = [np.squeeze(mask, axis=1) if len(mask.shape) > 3 else mask for mask in masks]
101
+ scores = [np.squeeze(score) for score in scores]
102
+ logits = [np.squeeze(logit, axis=1) if len(logit.shape) > 3 else logit for logit in logits]
103
+ return masks, scores, logits
lang_sam/models/utils.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ import torch
4
+
5
+
6
+ def get_device_type() -> str:
7
+ if torch.backends.mps.is_available():
8
+ return "mps"
9
+ elif torch.cuda.is_available():
10
+ return "cuda"
11
+ else:
12
+ logging.warning("No GPU found, using CPU instead")
13
+ return "cpu"
lang_sam/server.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+
3
+ import litserve as ls
4
+ import numpy as np
5
+ from fastapi import Response, UploadFile
6
+ from PIL import Image
7
+
8
+ from lang_sam import LangSAM
9
+ from lang_sam.utils import draw_image
10
+
11
+ PORT = 8000
12
+
13
+
14
+ class LangSAMAPI(ls.LitAPI):
15
+ def setup(self, device: str) -> None:
16
+ """Initialize or load the LangSAM model."""
17
+ self.model = LangSAM(sam_type="sam2.1_hiera_small")
18
+ print("LangSAM model initialized.")
19
+
20
+ def decode_request(self, request) -> dict:
21
+ """Decode the incoming request to extract parameters and image bytes.
22
+
23
+ Assumes the request is sent as multipart/form-data with fields:
24
+ - sam_type: str
25
+ - box_threshold: float
26
+ - text_threshold: float
27
+ - text_prompt: str
28
+ - image: UploadFile
29
+ """
30
+ # Extract form data
31
+ sam_type = request.get("sam_type")
32
+ box_threshold = float(request.get("box_threshold", 0.3))
33
+ text_threshold = float(request.get("text_threshold", 0.25))
34
+ text_prompt = request.get("text_prompt", "")
35
+
36
+ # Extract image file
37
+ image_file: UploadFile = request.get("image")
38
+ if image_file is None:
39
+ raise ValueError("No image file provided in the request.")
40
+
41
+ image_bytes = image_file.file.read()
42
+
43
+ return {
44
+ "sam_type": sam_type,
45
+ "box_threshold": box_threshold,
46
+ "text_threshold": text_threshold,
47
+ "image_bytes": image_bytes,
48
+ "text_prompt": text_prompt,
49
+ }
50
+
51
+ def predict(self, inputs: dict) -> dict:
52
+ """Perform prediction using the LangSAM model.
53
+
54
+ Yields:
55
+ dict: Contains the processed output image.
56
+ """
57
+ print("Starting prediction with parameters:")
58
+ print(
59
+ f"sam_type: {inputs['sam_type']}, \
60
+ box_threshold: {inputs['box_threshold']}, \
61
+ text_threshold: {inputs['text_threshold']}, \
62
+ text_prompt: {inputs['text_prompt']}"
63
+ )
64
+
65
+ if inputs["sam_type"] != self.model.sam_type:
66
+ print(f"Updating SAM model type to {inputs['sam_type']}")
67
+ self.model.sam.build_model(inputs["sam_type"])
68
+
69
+ try:
70
+ image_pil = Image.open(BytesIO(inputs["image_bytes"])).convert("RGB")
71
+ except Exception as e:
72
+ raise ValueError(f"Invalid image data: {e}")
73
+
74
+ results = self.model.predict(
75
+ images_pil=[image_pil],
76
+ texts_prompt=[inputs["text_prompt"]],
77
+ box_threshold=inputs["box_threshold"],
78
+ text_threshold=inputs["text_threshold"],
79
+ )
80
+ results = results[0]
81
+
82
+ if not len(results["masks"]):
83
+ print("No masks detected. Returning original image.")
84
+ return {"output_image": image_pil}
85
+
86
+ # Draw results on the image
87
+ image_array = np.asarray(image_pil)
88
+ output_image = draw_image(
89
+ image_array,
90
+ results["masks"],
91
+ results["boxes"],
92
+ results["scores"],
93
+ results["labels"],
94
+ )
95
+ output_image = Image.fromarray(np.uint8(output_image)).convert("RGB")
96
+
97
+ return {"output_image": output_image}
98
+
99
+ def encode_response(self, output: dict) -> Response:
100
+ """Encode the prediction result into an HTTP response.
101
+
102
+ Returns:
103
+ Response: Contains the processed image in PNG format.
104
+ """
105
+ try:
106
+ image = output["output_image"]
107
+ buffer = BytesIO()
108
+ image.save(buffer, format="PNG")
109
+ buffer.seek(0)
110
+ return Response(content=buffer.getvalue(), media_type="image/png")
111
+ except StopIteration:
112
+ raise ValueError("No output generated by the prediction.")
113
+
114
+
115
+ lit_api = LangSAMAPI()
116
+ server = ls.LitServer(lit_api)
117
+
118
+
119
+ if __name__ == "__main__":
120
+ print(f"Starting LitServe and Gradio server on port {PORT}...")
121
+ server.run(port=PORT)
lang_sam/utils.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import supervision as sv
4
+ from PIL import Image
5
+
6
+ MIN_AREA = 100
7
+
8
+
9
+ def load_image(image_path: str):
10
+ return Image.open(image_path).convert("RGB")
11
+
12
+
13
+ def draw_image(image_rgb, masks, xyxy, probs, labels):
14
+ box_annotator = sv.BoxCornerAnnotator()
15
+ label_annotator = sv.LabelAnnotator()
16
+ mask_annotator = sv.MaskAnnotator()
17
+ # Create class_id for each unique label
18
+ unique_labels = list(set(labels))
19
+ class_id_map = {label: idx for idx, label in enumerate(unique_labels)}
20
+ class_id = [class_id_map[label] for label in labels]
21
+
22
+ # Add class_id to the Detections object
23
+ detections = sv.Detections(
24
+ xyxy=xyxy,
25
+ mask=masks.astype(bool),
26
+ confidence=probs,
27
+ class_id=np.array(class_id),
28
+ )
29
+ annotated_image = box_annotator.annotate(scene=image_rgb.copy(), detections=detections)
30
+ annotated_image = label_annotator.annotate(scene=annotated_image, detections=detections, labels=labels)
31
+ annotated_image = mask_annotator.annotate(scene=annotated_image, detections=detections)
32
+ return annotated_image
33
+
34
+
35
+ def get_contours(mask):
36
+ if len(mask.shape) > 2:
37
+ mask = np.squeeze(mask, 0)
38
+ mask = mask.astype(np.uint8)
39
+ mask *= 255
40
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
41
+ effContours = []
42
+ for c in contours:
43
+ area = cv2.contourArea(c)
44
+ if area > MIN_AREA:
45
+ effContours.append(c)
46
+ return effContours
47
+
48
+
49
+ def contour_to_points(contour):
50
+ pointsNum = len(contour)
51
+ contour = contour.reshape(pointsNum, -1).astype(np.float32)
52
+ points = [point.tolist() for point in contour]
53
+ return points
54
+
55
+
56
+ def generate_labelme_json(binary_masks, labels, image_size, image_path=None):
57
+ """Generate a LabelMe format JSON file from binary mask tensor.
58
+
59
+ Args:
60
+ binary_masks: Binary mask tensor of shape [N, H, W].
61
+ labels: List of labels for each mask.
62
+ image_size: Tuple of (height, width) for the image size.
63
+ image_path: Path to the image file (optional).
64
+
65
+ Returns:
66
+ A dictionary representing the LabelMe JSON file.
67
+ """
68
+ num_masks = binary_masks.shape[0]
69
+ binary_masks = binary_masks.numpy()
70
+
71
+ json_dict = {
72
+ "version": "4.5.6",
73
+ "imageHeight": image_size[0],
74
+ "imageWidth": image_size[1],
75
+ "imagePath": image_path,
76
+ "flags": {},
77
+ "shapes": [],
78
+ "imageData": None,
79
+ }
80
+
81
+ # Loop through the masks and add them to the JSON dictionary
82
+ for i in range(num_masks):
83
+ mask = binary_masks[i]
84
+ label = labels[i]
85
+ effContours = get_contours(mask)
86
+
87
+ for effContour in effContours:
88
+ points = contour_to_points(effContour)
89
+ shape_dict = {
90
+ "label": label,
91
+ "line_color": None,
92
+ "fill_color": None,
93
+ "points": points,
94
+ "shape_type": "polygon",
95
+ }
96
+
97
+ json_dict["shapes"].append(shape_dict)
98
+
99
+ return json_dict
pyproject.toml ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lang-sam"
7
+ version = "0.2.1"
8
+ description = "Language segment-anything"
9
+ readme = "README.md"
10
+ authors = [
11
+ { name = "Luca Medeiros", email = "[email protected]" },
12
+ ]
13
+ requires-python = ">=3.11"
14
+ dynamic = ["dependencies"]
15
+
16
+ [tool.setuptools.dynamic]
17
+ dependencies = {file = ["requirements.txt"]}
18
+
19
+ [tool.setuptools.packages.find]
20
+ where = ["."]
21
+ include = ["lang_sam", "lang_sam.*"]
22
+
23
+ [tool.ruff]
24
+ target-version = "py311"
25
+ line-length = 120
26
+ fix = true
27
+ select = [
28
+ # https://github.com/charliermarsh/ruff#pyflakes-f
29
+ "F", # Pyflakes
30
+ # https://github.com/charliermarsh/ruff#pycodestyle-e-w
31
+ "E", # pycodestyle
32
+ "W", # Warning
33
+ # https://github.com/charliermarsh/ruff#flake8-comprehensions-c4
34
+ # https://github.com/charliermarsh/ruff#mccabe-c90
35
+ "C", # Complexity (mccabe+) & comprehensions
36
+ # https://github.com/charliermarsh/ruff#pyupgrade-up
37
+ "UP", # pyupgrade
38
+ # https://github.com/charliermarsh/ruff#isort-i
39
+ "I", # isort
40
+ ]
41
+ ignore = [
42
+ # https://github.com/charliermarsh/ruff#pycodestyle-e-w
43
+ "E402", # module level import not at top of file
44
+ # https://github.com/charliermarsh/ruff#pyupgrade-up
45
+ "UP006", # use-pep585-annotation
46
+ "UP007", # use-pep604-annotation
47
+ "E741", # Ambiguous variable name
48
+ ]
49
+ [tool.ruff.per-file-ignores]
50
+ "__init__.py" = [
51
+ "F401", # unused import
52
+ "F403", # star imports
53
+ ]
54
+
55
+ [tool.ruff.mccabe]
56
+ max-complexity = 24
57
+
58
+ [tool.ruff.pydocstyle]
59
+ convention = "numpy"
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio==5.0.2
2
+ litserve==0.2.3
3
+ opencv-python-headless==4.10.0.84
4
+ pydantic==2.9.2
5
+ sam-2 @ git+https://github.com/facebookresearch/segment-anything-2@c2ec8e14a185632b0a5d8b161928ceb50197eddc
6
+ supervision==0.23.0 ; python_full_version > '3.10'
7
+ transformers==4.44.2
8
+ uvloop==0.20.0
9
+ torch==2.4.1
10
+ torchvision==0.19.1