Repository: roboflow/supervision
File: supervision/detection/core.py (Python)

Code before:
            processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
            model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")

            image = Image.open(<SOURCE_IMAGE_PATH>)
            inputs = processor(images=image, return_tensors="pt")

            with torch.no_grad():
                outputs = model(**inputs)

            width, height = image.size
            target_size = torch.tensor([[height, width]])
            results = processor.post_process_object_detection(
                outputs=outputs, target_sizes=target_size)[0]

            detections = sv.Detections.from_transformers(
                transformers_results=results,
                id2label=model.config.id2label
            )
            ```

        !!! tip

            Class names values can be accessed using `detections["class_name"]`.
        """  # noqa: E501 // docs

        data = {}

        if transformers_results.__class__.__name__ == "Tensor":
            segmentation_array = transformers_results.cpu().detach().numpy()

            class_ids = np.unique(segmentation_array)

            masks = np.stack(
                [
                    (segmentation_array == class_id).astype(bool)
                    for class_id in class_ids
                ],
                axis=0,
            )

            if id2label is not None:
                class_names = np.array([id2label[class_id] for class_id in class_ids])
                data[CLASS_NAME_DATA_FIELD] = class_names

            return cls(
                xyxy=mask_to_xyxy(masks),
                mask=masks,
                class_id=class_ids,
                data=data,
            )


Review comment (refactor):
In `from_transformers`, there are four places where we do:

```python
if id2label is not None:
    class_names = np.array([id2label[class_id] for class_id in class_ids])
    data[CLASS_NAME_DATA_FIELD] = class_names
```

I'd wrap it in a local helper function. It can be defined inside `from_transformers`.

```python
def get_data(class_ids: np.ndarray, id2label: Optional[Dict[int, str]]) -> dict:
    data = {}
    if id2label is not None:
        class_names = np.array([id2label[class_id] for class_id in class_ids])
        data[CLASS_NAME_DATA_FIELD] = class_names
    return data
``` 

Code after:
            from PIL import Image
            from transformers import DetrImageProcessor, DetrForObjectDetection

            processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
            model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")

            image = Image.open(<SOURCE_IMAGE_PATH>)
            inputs = processor(images=image, return_tensors="pt")

            with torch.no_grad():
                outputs = model(**inputs)

            width, height = image.size
            target_size = torch.tensor([[height, width]])
            results = processor.post_process_object_detection(
                outputs=outputs, target_sizes=target_size)[0]

            detections = sv.Detections.from_transformers(
                transformers_results=results,
                id2label=model.config.id2label
            )
            ```
        """  # noqa: E501 // docs

        if (
            transformers_results.__class__.__name__ == "Tensor"
            or "segmentation" in transformers_results
        ):
            return cls(
                **process_transformers_v5_segmentation_result(
                    transformers_results, id2label
                )
            )

        if "masks" in transformers_results or "png_string" in transformers_results:
            return cls(
                **process_transformers_v4_segmentation_result(
                    transformers_results, id2label
                )
            )

        if "boxes" in transformers_results:
            return cls(
                **process_transformers_detection_result(transformers_results, id2label)
            )

    @classmethod
    def from_detectron2(cls, detectron2_results) -> Detections:
        """
        Create a Detections object from the
        [Detectron2](https://github.com/facebookresearch/detectron2) inference result.