from __future__ import annotations

from copy import deepcopy
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, cast

import numpy as np
import numpy.typing as npt

from supervision.config import ORIENTED_BOX_COORDINATES
from supervision.detection.compact_mask import CompactMask
from supervision.detection.core import Detections
from supervision.detection.utils.iou_and_nms import (
    box_iou_batch,
    mask_iou_batch,
    oriented_box_iou_batch,
)
from supervision.draw.color import LEGACY_COLOR_PALETTE
from supervision.metrics.core import Metric, MetricTarget
from supervision.metrics.utils.matching import (
    _match_detection_batch_with_target_indices,
)
from supervision.metrics.utils.object_size import (
    ObjectSizeCategory,
    get_detection_size_category,
)
from supervision.metrics.utils.utils import ensure_pandas_installed

if TYPE_CHECKING:
    import pandas as pd


@dataclass
class MeanAverageRecallResult:
    """
    The results of the Mean Average Recall metric calculation.

    Defaults to `0` if no detections or targets were provided.

    Attributes:
        metric_target: the type of data used for the metric -
            boxes, masks or oriented bounding boxes.
        mAR_at_1: the Mean Average Recall, when considering only the top
            highest confidence detection for each image.
        mAR_at_10: the Mean Average Recall, when considering top 10
            highest confidence detections for each image.
        mAR_at_100: the Mean Average Recall, when considering top 100
            highest confidence detections for each image.
        recall_per_class: the recall scores per max detection count, class and
            IoU threshold. Shape:
            `(num_max_detections, num_target_classes, num_iou_thresholds)`.
        max_detections: the array with maximum number of detections
            considered.
        iou_thresholds: the IoU thresholds used in the calculations.
        matched_classes: the class IDs of all matched classes.
            Corresponds to the class axis of `recall_per_class`.
        small_objects: the Mean Average Recall
            metric results for small objects (area < 32²).
        medium_objects: the Mean Average Recall
            metric results for medium objects (32² ≤ area < 96²).
        large_objects: the Mean Average Recall
            metric results for large objects (area ≥ 96²).
    """

    metric_target: MetricTarget

    @property
    def mAR_at_1(self) -> float:
        return float(self.recall_scores[0])

    @property
    def mAR_at_10(self) -> float:
        return float(self.recall_scores[1])

    @property
    def mAR_at_100(self) -> float:
        return float(self.recall_scores[2])

    recall_scores: npt.NDArray[np.float64]
    recall_per_class: npt.NDArray[np.float64]
    max_detections: npt.NDArray[np.int32]
    iou_thresholds: npt.NDArray[np.float32]
    matched_classes: npt.NDArray[np.int32]

    small_objects: MeanAverageRecallResult | None
    medium_objects: MeanAverageRecallResult | None
    large_objects: MeanAverageRecallResult | None

    def __str__(self) -> str:
        """
        Format as a pretty string.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> from supervision.metrics import MeanAverageRecall
            >>> predictions = sv.Detections(
            ...     xyxy=np.array([[0, 0, 10, 10]]),
            ...     class_id=np.array([0]),
            ...     confidence=np.array([0.9])
            ... )
            >>> targets = sv.Detections(
            ...     xyxy=np.array([[0, 0, 10, 10]]),
            ...     class_id=np.array([0])
            ... )
            >>> mar_metric = MeanAverageRecall()
            >>> mar_result = mar_metric.update(predictions, targets).compute()
            >>> print(mar_result)  # doctest: +ELLIPSIS
            MeanAverageRecallResult:
            Metric target:  MetricTarget.BOXES
            mAR @ 1:    1.0000
            mAR @ 10:   1.0000
            mAR @ 100:  1.0000
            max detections: [  1  10 100]
            IoU thresh:     [0.5  0.55 ... 0.95]
            mAR per class:
              @1:
                0: [1. ... 1.]
              @10:
                0: [1. ... 1.]
              @100:
                0: [1. ... 1.]
            ...
            Medium objects:
              MeanAverageRecallResult:
              Metric target:  MetricTarget.BOXES
              mAR @ 1:    0.0000
              ...

            ```
        """
        out_str = (
            f"{self.__class__.__name__}:\n"
            f"Metric target:  {self.metric_target}\n"
            f"mAR @ 1:    {self.mAR_at_1:.4f}\n"
            f"mAR @ 10:   {self.mAR_at_10:.4f}\n"
            f"mAR @ 100:  {self.mAR_at_100:.4f}\n"
            f"max detections: {self.max_detections}\n"
            f"IoU thresh:     {self.iou_thresholds}\n"
            f"mAR per class:\n"
        )
        if self.recall_per_class.size == 0:
            out_str += "  No results\n"
        for max_detections, recalls_at_k in zip(
            self.max_detections, self.recall_per_class
        ):
            out_str += f"  @{max_detections}:\n"
            for class_id, recall_of_class in zip(self.matched_classes, recalls_at_k):
                out_str += f"    {class_id}: {recall_of_class}\n"

        indent = "  "
        if self.small_objects is not None:
            indented = indent + str(self.small_objects).replace("\n", f"\n{indent}")
            out_str += f"\nSmall objects:\n{indented}"
        if self.medium_objects is not None:
            indented = indent + str(self.medium_objects).replace("\n", f"\n{indent}")
            out_str += f"\nMedium objects:\n{indented}"
        if self.large_objects is not None:
            indented = indent + str(self.large_objects).replace("\n", f"\n{indent}")
            out_str += f"\nLarge objects:\n{indented}"

        return out_str

    def to_pandas(self) -> pd.DataFrame:
        """
        Convert the result to a pandas DataFrame.

        Returns:
            The result as a DataFrame.
        """
        ensure_pandas_installed()
        import pandas as pd

        pandas_data: dict[str, Any] = {
            "mAR @ 1": self.mAR_at_1,
            "mAR @ 10": self.mAR_at_10,
            "mAR @ 100": self.mAR_at_100,
        }

        if self.small_objects is not None:
            small_objects_df = self.small_objects.to_pandas()
            for key, value in small_objects_df.items():
                pandas_data[f"small_objects_{key}"] = value
        if self.medium_objects is not None:
            medium_objects_df = self.medium_objects.to_pandas()
            for key, value in medium_objects_df.items():
                pandas_data[f"medium_objects_{key}"] = value
        if self.large_objects is not None:
            large_objects_df = self.large_objects.to_pandas()
            for key, value in large_objects_df.items():
                pandas_data[f"large_objects_{key}"] = value

        return pd.DataFrame(pandas_data, index=[0])

    def plot(self) -> None:
        """
        Plot the Mean Average Recall results.

        ![example_plot](\
            https://media.roboflow.com/supervision-docs/metrics/mAR_plot_example.png\
            ){ align=center width="800" }
        """
        from matplotlib import pyplot as plt

        labels = ["mAR @ 1", "mAR @ 10", "mAR @ 100"]
        values = [self.mAR_at_1, self.mAR_at_10, self.mAR_at_100]
        colors = [LEGACY_COLOR_PALETTE[0]] * 3

        if self.small_objects is not None:
            small_objects = self.small_objects
            labels += ["Small: mAR @ 1", "Small: mAR @ 10", "Small: mAR @ 100"]
            values += [
                small_objects.mAR_at_1,
                small_objects.mAR_at_10,
                small_objects.mAR_at_100,
            ]
            colors += [LEGACY_COLOR_PALETTE[3]] * 3

        if self.medium_objects is not None:
            medium_objects = self.medium_objects
            labels += ["Medium: mAR @ 1", "Medium: mAR @ 10", "Medium: mAR @ 100"]
            values += [
                medium_objects.mAR_at_1,
                medium_objects.mAR_at_10,
                medium_objects.mAR_at_100,
            ]
            colors += [LEGACY_COLOR_PALETTE[2]] * 3

        if self.large_objects is not None:
            large_objects = self.large_objects
            labels += ["Large: mAR @ 1", "Large: mAR @ 10", "Large: mAR @ 100"]
            values += [
                large_objects.mAR_at_1,
                large_objects.mAR_at_10,
                large_objects.mAR_at_100,
            ]
            colors += [LEGACY_COLOR_PALETTE[4]] * 3

        plt.rcParams["font.family"] = "monospace"

        _, ax = plt.subplots(figsize=(10, 6))
        ax.set_ylim(0, 1)
        ax.set_ylabel("Value", fontweight="bold")
        title = (
            f"Mean Average Recall, by Object Size\n(target: {self.metric_target.value})"
        )
        ax.set_title(title, fontweight="bold")

        x_positions = range(len(labels))
        bars = ax.bar(x_positions, values, color=colors, align="center")

        ax.set_xticks(x_positions)
        ax.set_xticklabels(labels, rotation=45, ha="right")

        for bar in bars:
            y_value = bar.get_height()
            ax.text(
                bar.get_x() + bar.get_width() / 2,
                y_value + 0.02,
                f"{y_value:.2f}",
                ha="center",
                va="bottom",
            )

        plt.rcParams["font.family"] = "sans-serif"

        plt.tight_layout()
        plt.show()


class MeanAverageRecall(Metric["MeanAverageRecallResult"]):
    """
    Mean Average Recall (mAR) measures how well the model detects
    and retrieves relevant objects by averaging recall over multiple
    IoU thresholds, classes and detection limits.

    Intuitively, while Recall measures the ability to find all relevant
    objects, mAR narrows down how many detections are considered for each
    image. For example, mAR @ 100 considers the top 100 highest confidence
    detections for each image. mAR @ 1 considers only the highest
    confidence detection for each image.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> from supervision.metrics import MeanAverageRecall
        >>> predictions = sv.Detections(
        ...     xyxy=np.array([[0, 0, 10, 10]]),
        ...     class_id=np.array([0]),
        ...     confidence=np.array([0.9])
        ... )
        >>> targets = sv.Detections(
        ...     xyxy=np.array([[0, 0, 10, 10]]),
        ...     class_id=np.array([0])
        ... )
        >>> mar_metric = MeanAverageRecall()
        >>> mar_result = mar_metric.update(predictions, targets).compute()
        >>> round(float(mar_result.mAR_at_100), 2)
        1.0

        ```

    ![example_plot](
        https://media.roboflow.com/supervision-docs/metrics/mAR_plot_example.png
    ){ align=center width="800" }
    """

    def __init__(
        self,
        metric_target: MetricTarget = MetricTarget.BOXES,
    ):
        """
        Initialize the Mean Average Recall metric.

        Args:
            metric_target: The type of detection data to use.
        """
        self._metric_target = metric_target

        self._predictions_list: list[Detections] = []
        self._targets_list: list[Detections] = []

        self.max_detections = np.array([1, 10, 100])

    def reset(self) -> None:
        """
        Reset the metric to its initial state, clearing all stored data.
        """
        self._predictions_list = []
        self._targets_list = []

    def update(
        self,
        predictions: Detections | list[Detections],
        targets: Detections | list[Detections],
    ) -> MeanAverageRecall:
        """
        Add new predictions and targets to the metric, but do not compute the result.

        Args:
            predictions: The predicted detections.
            targets: The target detections.

        Returns:
            The updated metric instance.
        """
        if not isinstance(predictions, list):
            predictions = [predictions]
        if not isinstance(targets, list):
            targets = [targets]

        if len(predictions) != len(targets):
            raise ValueError(
                f"The number of predictions ({len(predictions)}) and"
                f" targets ({len(targets)}) during the update must be the same."
            )

        self._predictions_list.extend(predictions)
        self._targets_list.extend(targets)

        return self

    def compute(self) -> MeanAverageRecallResult:
        """
        Calculate the Mean Average Recall metric based on the stored predictions
        and ground-truth, at different IoU thresholds and maximum detection counts.

        Returns:
            The Mean Average Recall metric result.
        """
        result = self._compute(self._predictions_list, self._targets_list)
        result.small_objects = self._compute(
            self._predictions_list, self._targets_list, ObjectSizeCategory.SMALL
        )
        result.medium_objects = self._compute(
            self._predictions_list, self._targets_list, ObjectSizeCategory.MEDIUM
        )
        result.large_objects = self._compute(
            self._predictions_list, self._targets_list, ObjectSizeCategory.LARGE
        )

        return result

    def _compute(
        self,
        predictions_list: list[Detections],
        targets_list: list[Detections],
        size_category: ObjectSizeCategory = ObjectSizeCategory.ANY,
    ) -> MeanAverageRecallResult:
        if size_category != ObjectSizeCategory.ANY:
            # Recall is unaffected by false-positive bookkeeping, and out-of-bucket
            # predictions must still consume top-K rank slots, so bucket-filtering
            # the targets is all the size handling mAR needs.
            targets_list = [
                self._filter_detections_by_size(targets, size_category)
                for targets in targets_list
            ]

        iou_thresholds = np.linspace(0.5, 0.95, 10, dtype=np.float32)
        stats: list[Any] = []

        for predictions, targets in zip(predictions_list, targets_list):
            prediction_contents = self._detections_content(predictions)
            target_contents = self._detections_content(targets)
            if len(targets) > 0:
                if predictions.class_id is None or targets.class_id is None:
                    raise ValueError(
                        "MeanAverageRecall metric requires `class_id` on both "
                        "predictions and targets."
                    )
                if len(predictions) == 0:
                    target_class_ids = np.asarray(targets.class_id, dtype=np.int32)
                    if len(target_class_ids) == 0:
                        continue
                    stats.append(
                        (
                            np.zeros((0, iou_thresholds.size), dtype=bool),
                            np.zeros((0, iou_thresholds.size), dtype=bool),
                            np.zeros((0,), dtype=int),
                            np.zeros((0,), dtype=int),
                            target_class_ids,
                        )
                    )

                else:
                    if predictions.confidence is None:
                        raise ValueError(
                            "MeanAverageRecall metric requires `confidence` on "
                            "predictions."
                        )
                    prediction_class_ids = np.asarray(
                        predictions.class_id, dtype=np.int32
                    )
                    target_class_ids = np.asarray(targets.class_id, dtype=np.int32)
                    prediction_confidence = np.asarray(
                        predictions.confidence, dtype=np.float32
                    )
                    if self._metric_target == MetricTarget.BOXES:
                        # BOXES target never yields CompactMask; narrow for mypy.
                        iou = box_iou_batch(
                            cast(npt.NDArray[np.number], target_contents),
                            cast(npt.NDArray[np.number], prediction_contents),
                        )
                    elif self._metric_target == MetricTarget.MASKS:
                        iou = mask_iou_batch(target_contents, prediction_contents)
                    elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
                        # OBB target never yields CompactMask; narrow for mypy.
                        iou = oriented_box_iou_batch(
                            cast(npt.NDArray[np.number], target_contents),
                            cast(npt.NDArray[np.number], prediction_contents),
                        )
                    else:
                        raise ValueError(
                            "Unsupported metric target for IoU calculation"
                        )

                    matches, _ = _match_detection_batch_with_target_indices(
                        prediction_class_ids,
                        target_class_ids,
                        iou,
                        iou_thresholds,
                    )
                    ignored_matches = np.zeros_like(matches, dtype=bool)

                    sorted_indices = np.argsort(-prediction_confidence)
                    stats.append(
                        (
                            matches[sorted_indices],
                            ignored_matches[sorted_indices],
                            np.arange(len(prediction_confidence)),
                            prediction_class_ids[sorted_indices],
                            target_class_ids,
                        )
                    )

        if not stats:
            max_detection_count = self.max_detections.shape[0]
            return MeanAverageRecallResult(
                metric_target=self._metric_target,
                recall_scores=np.zeros(max_detection_count),
                recall_per_class=np.zeros(
                    (max_detection_count, 0, iou_thresholds.shape[0])
                ),
                max_detections=self.max_detections,
                iou_thresholds=iou_thresholds,
                matched_classes=np.array([], dtype=int),
                small_objects=None,
                medium_objects=None,
                large_objects=None,
            )

        concatenated_stats = [np.concatenate(items, 0) for items in zip(*stats)]
        recall_scores_per_k, recall_per_class_at_k, unique_classes = (
            self._compute_average_recall_for_classes(*concatenated_stats)
        )

        return MeanAverageRecallResult(
            metric_target=self._metric_target,
            recall_scores=recall_scores_per_k,
            recall_per_class=recall_per_class_at_k,
            max_detections=self.max_detections,
            iou_thresholds=iou_thresholds,
            matched_classes=unique_classes,
            small_objects=None,
            medium_objects=None,
            large_objects=None,
        )

    def _compute_average_recall_for_classes(
        self,
        matches: npt.NDArray[np.bool_],
        ignored_matches: npt.NDArray[np.bool_],
        prediction_indices: npt.NDArray[np.int32],
        prediction_class_ids: npt.NDArray[np.int32],
        true_class_ids: npt.NDArray[np.int32],
    ) -> tuple[
        npt.NDArray[np.float64],
        npt.NDArray[np.float64],
        npt.NDArray[np.int32],
    ]:
        unique_classes, class_counts = np.unique(true_class_ids, return_counts=True)

        if unique_classes.size == 0:
            max_detection_count = self.max_detections.shape[0]
            num_thresholds = matches.shape[1]
            return (
                np.zeros(max_detection_count, dtype=np.float64),
                np.zeros((max_detection_count, 0, num_thresholds), dtype=np.float64),
                unique_classes,
            )

        recalls_at_k: list[npt.NDArray[np.float64]] = []
        for max_detections in self.max_detections:
            # Shape: PxTh,P,C,C -> CxThx3
            is_within_limit = prediction_indices < max_detections
            confusion_matrix = self._compute_confusion_matrix(
                matches[is_within_limit],
                ignored_matches[is_within_limit],
                prediction_class_ids[is_within_limit],
                unique_classes,
                class_counts,
            )

            # Shape: CxThx3 -> CxTh
            recall_per_class = self._compute_recall(confusion_matrix)
            recalls_at_k.append(recall_per_class)

        # Shape: KxCxTh -> KxC
        recall_per_class_at_k = np.array(recalls_at_k)
        average_recall_per_class = np.mean(recall_per_class_at_k, axis=2)

        # Shape: KxC -> K
        recall_scores = np.mean(average_recall_per_class, axis=1)

        return recall_scores, recall_per_class_at_k, unique_classes

    @staticmethod
    def _match_detection_batch(
        predictions_classes: npt.NDArray[np.int32],
        target_classes: npt.NDArray[np.int32],
        iou: npt.NDArray[np.float32],
        iou_thresholds: npt.NDArray[np.float32],
    ) -> npt.NDArray[np.bool_]:
        result_correct, _ = _match_detection_batch_with_target_indices(
            predictions_classes, target_classes, iou, iou_thresholds
        )
        return result_correct

    @staticmethod
    def _compute_confusion_matrix(
        sorted_matches: npt.NDArray[np.bool_],
        sorted_ignored_matches: npt.NDArray[np.bool_],
        sorted_prediction_class_ids: npt.NDArray[np.int32],
        unique_classes: npt.NDArray[np.integer],
        class_counts: npt.NDArray[np.integer],
    ) -> npt.NDArray[np.float64]:
        """
        Compute the confusion matrix for each class and IoU threshold.

        Assumes the matches and prediction_class_ids are sorted by confidence
        in descending order.

        Args:
            sorted_matches: shape (P, Th), that is True
                if the prediction is a true positive at the given IoU threshold.
            sorted_ignored_matches: shape (P, Th), that is True
                if the prediction should not affect the given IoU threshold.
            sorted_prediction_class_ids: shape (P,), containing
                the class id for each prediction.
            unique_classes: shape (C,), containing the unique
                class ids.
            class_counts: shape (C,), containing the number
                of true instances for each class.
            max_detections: The maximum number of detections to
                consider for each class. Extra detections are considered false
                positives. By default, all detections are considered.

        Returns:
            shape (C, Th, 3), containing the true positives, false
                positives, and false negatives for each class and IoU threshold.
        """
        num_thresholds = sorted_matches.shape[1]
        num_classes = unique_classes.shape[0]

        confusion_matrix: npt.NDArray[np.float64] = np.zeros(
            (num_classes, num_thresholds, 3), dtype=np.float64
        )
        for class_idx, class_id in enumerate(unique_classes):
            is_class = sorted_prediction_class_ids == class_id
            num_true = class_counts[class_idx]
            num_predictions = is_class.sum()

            if num_predictions == 0:
                true_positives = np.zeros(num_thresholds)
                false_positives = np.zeros(num_thresholds)
                false_negatives = np.full(num_thresholds, num_true)
            elif num_true == 0:
                true_positives = np.zeros(num_thresholds)
                false_positives = (~sorted_ignored_matches[is_class]).sum(0)
                false_negatives = np.zeros(num_thresholds)
            else:
                limited_matches = sorted_matches[is_class]
                limited_ignored_matches = sorted_ignored_matches[is_class]
                true_positives = limited_matches.sum(0)

                false_positives = (~limited_matches & ~limited_ignored_matches).sum(0)
                false_negatives = num_true - true_positives

            confusion_matrix[class_idx] = np.stack(
                [true_positives, false_positives, false_negatives], axis=1
            )

        result_confusion_matrix: npt.NDArray[np.float64] = confusion_matrix
        return result_confusion_matrix

    @staticmethod
    def _compute_recall(
        confusion_matrix: npt.NDArray[np.float64],
    ) -> npt.NDArray[np.float64]:
        """
        Broadcastable function, computing the recall from the confusion matrix.

        Args:
            confusion_matrix: shape (N, ..., 3), where the last dimension
                contains the true positives, false positives, and false negatives.

        Returns:
            shape (N, ...), containing the recall for each element.
        """
        if not confusion_matrix.shape[-1] == 3:
            raise ValueError(
                f"Confusion matrix must have shape (..., 3), got "
                f"{confusion_matrix.shape}"
            )
        true_positives = confusion_matrix[..., 0]
        false_negatives = confusion_matrix[..., 2]

        denominator = true_positives + false_negatives
        recall = np.divide(
            true_positives,
            denominator,
            out=np.zeros_like(denominator, dtype=np.float64),
            where=denominator != 0,
        )

        result_recall: npt.NDArray[np.float64] = recall
        return result_recall

    def _detections_content(
        self, detections: Detections
    ) -> npt.NDArray[Any] | CompactMask:
        """Return boxes, masks or oriented bounding boxes from detections.

        For the mask target this may return a
        :class:`~supervision.detection.compact_mask.CompactMask` rather than a
        dense boolean array when the detections carry compact masks.
        """
        if self._metric_target == MetricTarget.BOXES:
            return cast(npt.NDArray[Any], detections.xyxy)
        if self._metric_target == MetricTarget.MASKS:
            if detections.mask is not None:
                # detections.mask is NDArray[bool] | CompactMask; return as-is.
                return detections.mask
            if len(detections) > 0:
                raise ValueError(
                    "MeanAverageRecall with `MetricTarget.MASKS` requires "
                    "detections to include masks."
                )
            return self._make_empty_content()
        if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
            obb = detections.data.get(ORIENTED_BOX_COORDINATES)
            if obb is not None and len(obb) > 0:
                result_obb: npt.NDArray[np.float32] = np.array(obb, dtype=np.float32)
                return result_obb
            return self._make_empty_content()
        raise ValueError(f"Invalid metric target: {self._metric_target}")

    def _make_empty_content(self) -> npt.NDArray[Any]:
        if self._metric_target == MetricTarget.BOXES:
            empty_boxes: npt.NDArray[np.float32] = np.empty((0, 4), dtype=np.float32)
            return empty_boxes

        if self._metric_target == MetricTarget.MASKS:
            empty_masks: npt.NDArray[np.bool_] = np.empty((0, 0, 0), dtype=bool)
            return empty_masks

        if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES:
            empty_obb: npt.NDArray[np.float32] = np.empty((0, 4, 2), dtype=np.float32)
            return empty_obb

        raise ValueError(f"Invalid metric target: {self._metric_target}")

    def _filter_detections_by_size(
        self, detections: Detections, size_category: ObjectSizeCategory
    ) -> Detections:
        """Return a copy of detections with contents filtered by object size."""
        new_detections = deepcopy(detections)
        if detections.is_empty() or size_category == ObjectSizeCategory.ANY:
            return new_detections

        sizes = get_detection_size_category(new_detections, self._metric_target)
        size_mask = sizes == size_category.value

        new_detections.xyxy = new_detections.xyxy[size_mask]
        if new_detections.mask is not None:
            new_detections.mask = new_detections.mask[size_mask]
        if new_detections.class_id is not None:
            new_detections.class_id = new_detections.class_id[size_mask]
        if new_detections.confidence is not None:
            new_detections.confidence = new_detections.confidence[size_mask]
        if new_detections.tracker_id is not None:
            new_detections.tracker_id = new_detections.tracker_id[size_mask]
        if new_detections.data is not None:
            for key, value in new_detections.data.items():
                new_detections.data[key] = np.array(value)[size_mask]

        return new_detections
