diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 37dde153..d31e07bd 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -7,7 +7,12 @@ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union import numpy as np from supervision.config import CLASS_NAME_DATA_FIELD, ORIENTED_BOX_COORDINATES -from supervision.detection.lmm import LMM, from_paligemma, validate_lmm_and_kwargs +from supervision.detection.lmm import ( + LMM, + from_florence_2, + from_paligemma, + validate_lmm_parameters, +) from supervision.detection.overlap_filter import ( box_non_max_merge, box_non_max_suppression, @@ -811,7 +816,9 @@ class Detections: ) @classmethod - def from_lmm(cls, lmm: Union[LMM, str], result: str, **kwargs) -> Detections: + def from_lmm( + cls, lmm: Union[LMM, str], result: Union[str, dict], **kwargs + ) -> Detections: """ Creates a Detections object from the given result string based on the specified Large Multimodal Model (LMM). @@ -847,13 +854,24 @@ class Detections: # array([0]) ``` """ - lmm = validate_lmm_and_kwargs(lmm, kwargs) + lmm = validate_lmm_parameters(lmm, result, kwargs) if lmm == LMM.PALIGEMMA: + assert isinstance(result, str) xyxy, class_id, class_name = from_paligemma(result, **kwargs) data = {CLASS_NAME_DATA_FIELD: class_name} return cls(xyxy=xyxy, class_id=class_id, data=data) + if lmm == LMM.FLORENCE_2: + assert isinstance(result, dict) + xyxy, labels, xyxyxyxy = from_florence_2(result, **kwargs) + data = {} + if labels is not None: + data[CLASS_NAME_DATA_FIELD] = labels + if xyxyxyxy is not None: + data[ORIENTED_BOX_COORDINATES] = xyxyxyxy + return cls(xyxy=xyxy, data=data) + raise ValueError(f"Unsupported LMM: {lmm}") @classmethod diff --git a/supervision/detection/lmm.py b/supervision/detection/lmm.py index 5f61db0a..910ca30c 100644 --- a/supervision/detection/lmm.py +++ b/supervision/detection/lmm.py @@ -4,17 +4,38 @@ from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np +from supervision.detection.utils import polygon_to_xyxy + class LMM(Enum): PALIGEMMA = "paligemma" + FLORENCE_2 = "florence_2" -REQUIRED_ARGUMENTS: Dict[LMM, List[str]] = {LMM.PALIGEMMA: ["resolution_wh"]} +RESULT_TYPES: Dict[LMM, type] = {LMM.PALIGEMMA: str, LMM.FLORENCE_2: dict} -ALLOWED_ARGUMENTS: Dict[LMM, List[str]] = {LMM.PALIGEMMA: ["resolution_wh", "classes"]} +REQUIRED_ARGUMENTS: Dict[LMM, List[str]] = { + LMM.PALIGEMMA: ["resolution_wh"], + LMM.FLORENCE_2: [], +} + +ALLOWED_ARGUMENTS: Dict[LMM, List[str]] = { + LMM.PALIGEMMA: ["resolution_wh", "classes"], + LMM.FLORENCE_2: [], +} + +SUPPORTED_TASKS_FLORENCE_2 = [ + "", + "", + "", + "", + "", +] -def validate_lmm_and_kwargs(lmm: Union[LMM, str], kwargs: Dict[str, Any]) -> LMM: +def validate_lmm_parameters( + lmm: Union[LMM, str], result: Any, kwargs: Dict[str, Any] +) -> LMM: if isinstance(lmm, str): try: lmm = LMM(lmm.lower()) @@ -23,6 +44,11 @@ def validate_lmm_and_kwargs(lmm: Union[LMM, str], kwargs: Dict[str, Any]) -> LMM f"Invalid lmm value: {lmm}. Must be one of {[e.value for e in LMM]}" ) + if not isinstance(result, RESULT_TYPES[lmm]): + raise ValueError( + f"Invalid LMM result type: {type(result)}. Must be {RESULT_TYPES[lmm]}" + ) + required_args = REQUIRED_ARGUMENTS.get(lmm, []) for arg in required_args: if arg not in kwargs: @@ -57,3 +83,49 @@ def from_paligemma( class_id = np.array([classes.index(name) for name in class_name]) return xyxy, class_id, class_name + + +def from_florence_2( + result: dict, +) -> Tuple[np.ndarray, Optional[np.ndarray], Optional[np.ndarray]]: + """ + Parse results from the Florence 2 multi-model model. + https://huggingface.co/microsoft/Florence-2-large + + Parameters: + result: dict containing the model output + + Returns: + xyxy (np.ndarray): An array of shape `(n, 4)` containing + the bounding boxes coordinates in format `[x1, y1, x2, y2]` + labels: (Optional[np.ndarray]): An array of shape `(n,)` containing + the class labels for each bounding box + obb_boxes: (Optional[np.ndarray]): An array of shape `(n, 4, 2)` containing + oriented bounding boxes. + """ + for task in ["", "", ""]: + if task in result: + result = result[task] + xyxy = np.array(result["bboxes"], dtype=np.float32) + labels = np.array(result["labels"]) + return xyxy, labels, None + + if "" in result: + result = result[""] + xyxy = np.array(result["bboxes"], dtype=np.float32) + # provides labels, but they are ["", "", "", ...] + return xyxy, None, None + + if "" in result: + result = result[""] + xyxyxyxy = np.array(result["quad_boxes"], dtype=np.float32) + xyxyxyxy = xyxyxyxy.reshape(-1, 4, 2) + xyxy = np.array([polygon_to_xyxy(polygon) for polygon in xyxyxyxy]) + + labels = np.array(result["labels"]) + return xyxy, labels, xyxyxyxy + + task = list(result.keys())[0] + raise NotImplementedError( + f"{task} task not supported. Supported tasks are: {SUPPORTED_TASKS_FLORENCE_2}" + )