Skip to content

Commit

Permalink
get endpoint ready for demo
Browse files Browse the repository at this point in the history
fixed tools.json

Update vision_agent/tools/tools.py

Bug fixes
  • Loading branch information
humpydonkey authored and AsiaCao committed Apr 3, 2024
1 parent 6db4ef3 commit f73ef58
Show file tree
Hide file tree
Showing 2 changed files with 194 additions and 36 deletions.
154 changes: 154 additions & 0 deletions vision_agent/tools/tools.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
[
{
"name": "image_question_answering",
"description": "answers a question about an image"
},
{
"name": "text_question_answering",
"description": "answers a question provided a context in text form"
},
{
"name": "image_captioning",
"description": "Generate a caption for the image. It can generate a brief description that can be used for image perception and image generation. For example: a) you can use this tool when you want to know what is it in the image\"; and b) when you want to generate a new image similar or resemble to input.png, you can use `image_captioning` to obtain the description about image input.png."
},
{
"name": "image_to_text",
"description": "Generate a description for the image. It can generate a detailed description that can be used for image perception and image generation. For example: a) you can use this tool when you want to know what is it in the image\"; and b) when you want to generate a new image similar or resemble to input.png, you can use `text_to_image` to obtain the description about image input.png."
},
{
"name": "image_to_edge",
"description": "get the edge map of the image."
},
{
"name": "image_to_line",
"description": "get the line map of the image."
},
{
"name": "image_to_hed",
"description": "get the HED map of the image."
},
{
"name": "image_to_scribble",
"description": "get the scribble of the image."
},
{
"name": "image_to_pose",
"description": "Get the pose of the image. It is usually used in image generation conditioned on pose map from input image."
},
{
"name": "image_to_depth",
"description": "get the depth map of the image."
},
{
"name": "image_to_normal",
"description": "get the normal map of the image."
},
{
"name": "object_detection",
"description": "detect all the objects in the image."
},
{
"name": "image_classification",
"description": "classify the objects in the image."
},
{
"name": "closed_set_image_classification",
"description": "Given a set of classes as a text prompt, classify the objects in the image based on the given classes."
},
{
"name": "panoptic_segmentation",
"description": "segment the common objects in the given image."
},
{
"name": "visual_grounding",
"description": "Visual Grounding (VG) aims to locate the most relevant object or region in an image, based on a natural language query. The query can be a phrase, a sentence or even a multi-round dialogue."
},
{
"name": "visual_grounding_segment",
"description": "Visual Grounding (VG) aims to locate the most relevant object or region in an image, based on a natural language query. The query can be a phrase, a sentence or even a multi-round dialogue."
},
{
"name": "optical_character_recognition",
"description": "Optical Character Recognition (OCR) is the process that converts an image of text into a machine-readable text format."
},
{
"name": "select_category",
"description": "select the target classes in category list with the given condition."
},
{
"name": "select_bbox",
"description": "select the bounding boxes with the given condition."
},
{
"name": "select_mask",
"description": "select the masks with the given condition."
},
{
"name": "count_categories",
"description": "count target categories in the given list."
},
{
"name": "count_objects",
"description": "count target objects in the given list. It is useful when you want to count the number of objects in the image"
},
{
"name": "count_masks",
"description": "count target mask in the given list."
},
{
"name": "video_captioning",
"description": "Generate a caption or description for video. It can generate a detailed description that can be used for video perception and video generation. For example: a) you can use this tool when you want to know what happened in the video\"; and b) when you want to generate tags for input video, you can use translate description obtained from `image_captioning` into tags."
},
{
"name": "video_classification",
"description": "Classify the video and detect the actions in the video."
},
{
"name": "frame_captioning",
"description": "Generate a caption or description for video every n seconds. It can generate a detailed description that can be used for video perception and video generation. For example: a) you can use this tool when you want to know what happened in the video\"; and b) when you want to generate tags for input video, you can use translate description obtained from `image_captioning` into tags."
},
{
"name": "frame_classification",
"description": "Classify the video and detect the actions in the every n seconds."
},
{
"name": "text_to_text_generation",
"description": "Text to text generation. It can be used for sentence acceptability judgment, Sentiment analysis, Paraphrasing/sentence similarity, Natural language inference, Sentence completion, Word sense disambiguation, Question answering."
},
{
"name": "openai_chat_model",
"description": "Answer the question by Large Language Model. It is useful for tasks such as generating content, answering questions, engaging in conversations and providing explanations. However, it still has some limitations. For example, it can not directly access the up-to-date information like time, weather, etc."
},
{
"name": "summarization",
"description": "Summarize sentences, long narratives, articles, papers, textbooks."
},
{
"name": "text_to_tags",
"description": "Predict the tags of text, article and papers by using the their textual content as input"
},
{
"name": "sentiment_analysis",
"description": "Sentiment analysis is the process of analyzing digital text to determine if the emotional tone of the message is positive, negative, or neutral."
}
]

input_keys: [
{ "image": "image file"},
{ "prompt": "text"},
{ "video": "video file"},
{ "context": "context for text qa"},
{ "tool": "tool name mentioned above"},
]

output_keys: [
{ "labels": "list of labels for image tasks"},
{ "scores": "list of scores for image and text tasks"},
{ "bboxes": "list of bounding boxes for detection tasks"},
{ "masks": "list of masks for segmentation tasks"},
{ "text": "list of text for text tasks"},
{ "frames": "list of frame numbers for video tasks"},
]



76 changes: 40 additions & 36 deletions vision_agent/tools/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class CLIP(Tool):
-------
>>> import vision_agent as va
>>> clip = va.tools.CLIP()
>>> clip(["red line", "yellow dot"], "ct_scan1.jpg"))
>>> clip("red line, yellow dot", "ct_scan1.jpg"))
[{"labels": ["red line", "yellow dot"], "scores": [0.98, 0.02]}]
"""

Expand All @@ -69,43 +69,43 @@ class CLIP(Tool):
description = "'clip_' is a tool that can classify or tag any image given a set of input classes or tags."
usage = {
"required_parameters": [
{"name": "prompt", "type": "List[str]"},
{"name": "prompt", "type": "str"},
{"name": "image", "type": "str"},
],
"examples": [
{
"scenario": "Can you classify this image as a cat? Image name: cat.jpg",
"parameters": {"prompt": ["cat"], "image": "cat.jpg"},
"parameters": {"prompt": "cat", "image": "cat.jpg"},
},
{
"scenario": "Can you tag this photograph with cat or dog? Image name: cat_dog.jpg",
"parameters": {"prompt": ["cat", "dog"], "image": "cat_dog.jpg"},
"parameters": {"prompt": "cat, dog", "image": "cat_dog.jpg"},
},
{
"scenario": "Can you build me a classifier that classifies red shirts, green shirts and other? Image name: shirts.jpg",
"parameters": {
"prompt": ["red shirt", "green shirt", "other"],
"prompt": "red shirt, green shirt, other",
"image": "shirts.jpg",
},
},
],
}

# TODO: Add support for input multiple images, which aligns with the output type.
def __call__(self, prompt: List[str], image: Union[str, ImageType]) -> Dict:
def __call__(self, prompt: str, image: Union[str, ImageType]) -> Dict:
"""Invoke the CLIP model.
Parameters:
prompt: a list of classes or tags to classify the image.
prompt: a string includes a list of classes or tags to classify the image.
image: the input image to classify.
Returns:
A list of dictionaries containing the labels and scores. Each dictionary contains the classification result for an image. E.g. [{"labels": ["red line", "yellow dot"], "scores": [0.98, 0.02]}]
"""
image_b64 = convert_to_b64(image)
data = {
"classes": prompt,
"images": [image_b64],
"prompt": prompt,
"image": image_b64,
}
res = requests.post(
self._ENDPOINT,
Expand Down Expand Up @@ -139,7 +139,7 @@ class GroundingDINO(Tool):
'scores': [0.98, 0.02]}]
"""

_ENDPOINT = "https://chnicr4kes5ku77niv2zoytggq0qyqlp.lambda-url.us-east-2.on.aws"
_ENDPOINT = "https://soi4ewr6fjqqdf5vuss6rrilee0kumxq.lambda-url.us-east-2.on.aws"

name = "grounding_dino_"
description = "'grounding_dino_' is a tool that can detect arbitrary objects with inputs such as category names or referring expressions."
Expand Down Expand Up @@ -182,7 +182,8 @@ def __call__(self, prompt: str, image: Union[str, Path, ImageType]) -> Dict:
image_b64 = convert_to_b64(image)
data = {
"prompt": prompt,
"images": [image_b64],
"image": image_b64,
"tool": "visual_grounding",
}
res = requests.post(
self._ENDPOINT,
Expand All @@ -195,16 +196,17 @@ def __call__(self, prompt: str, image: Union[str, Path, ImageType]) -> Dict:
) or "statusCode" not in resp_json:
_LOGGER.error(f"Request failed: {resp_json}")
raise ValueError(f"Request failed: {resp_json}")
resp_data = resp_json["data"]
for elt in resp_data:
if "bboxes" in elt:
elt["bboxes"] = [
normalize_bbox(box, image_size) for box in elt["bboxes"]
]
if "scores" in elt:
elt["scores"] = [round(score, 2) for score in elt["scores"]]
elt["size"] = (image_size[1], image_size[0])
return cast(Dict, resp_data)
data: Dict[str, Any] = resp_json["data"]
if "bboxes" in data:
data["bboxes"] = [
normalize_bbox(box, image_size) for box in data["bboxes"][0]
]
if "scores" in data:
data["scores"] = [round(score, 2) for score in data["scores"][0]]
if "labels" in data:
data["labels"] = [label for label in data["labels"][0]]
data["size"] = (image_size[1], image_size[0])
return data


class GroundingSAM(Tool):
Expand All @@ -215,7 +217,7 @@ class GroundingSAM(Tool):
-------
>>> import vision_agent as va
>>> t = va.tools.GroundingSAM()
>>> t(["red line", "yellow dot"], ct_scan1.jpg"])
>>> t("red line, yellow dot", "ct_scan1.jpg"])
[{'labels': ['yellow dot', 'red line'],
'bboxes': [[0.38, 0.15, 0.59, 0.7], [0.48, 0.25, 0.69, 0.71]],
'masks': [array([[0, 0, 0, ..., 0, 0, 0],
Expand All @@ -230,36 +232,36 @@ class GroundingSAM(Tool):
[1, 1, 1, ..., 1, 1, 1]], dtype=uint8)]}]
"""

_ENDPOINT = "https://cou5lfmus33jbddl6hoqdfbw7e0qidrw.lambda-url.us-east-2.on.aws"
_ENDPOINT = "https://soi4ewr6fjqqdf5vuss6rrilee0kumxq.lambda-url.us-east-2.on.aws"

name = "grounding_sam_"
description = "'grounding_sam_' is a tool that can detect and segment arbitrary objects with inputs such as category names or referring expressions."
usage = {
"required_parameters": [
{"name": "prompt", "type": "List[str]"},
{"name": "prompt", "type": "str"},
{"name": "image", "type": "str"},
],
"examples": [
{
"scenario": "Can you build me a car segmentor?",
"parameters": {"prompt": ["car"], "image": ""},
"parameters": {"prompt": "car", "image": ""},
},
{
"scenario": "Can you segment the person on the left? Image name: person.jpg",
"parameters": {"prompt": ["person on the left"], "image": "person.jpg"},
"parameters": {"prompt": "person on the left", "image": "person.jpg"},
},
{
"scenario": "Can you build me a tool that segments red shirts and green shirts? Image name: shirts.jpg",
"parameters": {
"prompt": ["red shirt", "green shirt"],
"prompt": "red shirt, green shirt",
"image": "shirts.jpg",
},
},
],
}

# TODO: Add support for input multiple images, which aligns with the output type.
def __call__(self, prompt: List[str], image: Union[str, ImageType]) -> Dict:
def __call__(self, prompt: str, image: Union[str, ImageType]) -> Dict:
"""Invoke the Grounding SAM model.
Parameters:
Expand All @@ -272,8 +274,9 @@ def __call__(self, prompt: List[str], image: Union[str, ImageType]) -> Dict:
image_size = get_image_size(image)
image_b64 = convert_to_b64(image)
data = {
"classes": prompt,
"prompt": prompt,
"image": image_b64,
"tool": "visual_grounding_segment",
}
res = requests.post(
self._ENDPOINT,
Expand All @@ -286,14 +289,15 @@ def __call__(self, prompt: List[str], image: Union[str, ImageType]) -> Dict:
) or "statusCode" not in resp_json:
_LOGGER.error(f"Request failed: {resp_json}")
raise ValueError(f"Request failed: {resp_json}")
resp_data = resp_json["data"]
data = resp_json["data"]
ret_pred: Dict[str, List] = {"labels": [], "bboxes": [], "masks": []}
for pred in resp_data["preds"]:
encoded_mask = pred["encoded_mask"]
mask = rle_decode(mask_rle=encoded_mask, shape=pred["mask_shape"])
ret_pred["labels"].append(pred["label_name"])
ret_pred["bboxes"].append(normalize_bbox(pred["bbox"], image_size))
ret_pred["masks"].append(mask)
data: Dict[str, Any] = resp_json["data"]
if "bboxes" in data:
data["bboxes"] = [
normalize_bbox(box, image_size) for box in data["bboxes"]
]
if "masks" in data:
data["masks"] = [rle_decode(mask_rle=mask, shape=data["mask_shape"]) for mask in data["masks"][0]]
return ret_pred


Expand Down

0 comments on commit f73ef58

Please sign in to comment.