a
    do                     @   s\  d dl Z d dlZd dlZd dlmZmZmZmZmZm	Z	m
Z
mZ d dlZd dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZmZmZ d dlmZ d d	lmZ d d
lmZm Z m!Z! d dl"m#Z#m$Z$ esdgZ%e!rd dl&m'Z' ndZ'g dZ%e r$d dl(m)Z* d dl+m,Z, d dl-m.Z. nd\Z,Z.dZ*g dZ%G dd deZ/e0ddddZ1dS )    N)AnyCallableDictListOptionalSequenceTupleUnion)apply_to_collection)Tensor)distributed)Literal)_fix_empty_tensors_input_validator_validate_iou_type_arg)Metric)rank_zero_warn)_MATPLOTLIB_AVAILABLE_PYCOCOTOOLS_AVAILABLE_TORCHVISION_GREATER_EQUAL_0_8)_AX_TYPE_PLOT_OUT_TYPEMeanAveragePrecision.plot)box_convert)r   MeanAveragePrecisionMeanAveragePrecision.tm_to_cocoMeanAveragePrecision.coco_to_tm)COCO)COCOeval)NNc                       s  e Zd ZU dZdZeed< dZee ed< dZ	eed< dZ
eed< d	Zeed
< ee ed< ee ed< ee ed< ee ed< ee ed< ee ed< ee ed< ee ed< ee ed< dZeed< dFed eed ee f eee  eee  eee  eeed edd
 fddZeeeef  eeeef  ddd d!Zed"d#d$Zed eeef d%d&d'Zeee eeeef d(d)d*ZedGeeeed ee f eeeeef  eeeef  f d+d,d-ZdHedd/d0d1Z dIeeef eeee ee f d2d3d4Z!ed"d5d6Z"dJee#j eee#j  eee#j  eee#j  eee#j  eee#j  ed7d8d9Z$dKeeeeef e%eeef  f  ee& e'd:d;d<Z(e)e#j*j+d= fd>d?Z,dLee) ee dd@ fdAdBZ-edMee ee ee dCdDdEZ.  Z/S )Nr   a2  Compute the `Mean-Average-Precision (mAP) and Mean-Average-Recall (mAR)`_ for object detection predictions.

    .. math::
        \text{mAP} = \frac{1}{n} \sum_{i=1}^{n} AP_i

    where :math:`AP_i` is the average precision for class :math:`i` and :math:`n` is the number of classes. The average
    precision is defined as the area under the precision-recall curve. For object detection the recall and precision are
    defined based on the intersection of union (IoU) between the predicted bounding boxes and the ground truth bounding
    boxes e.g. if two boxes have an IoU > t (with t being some threshold) they are considered a match and therefore
    considered a true positive. The precision is then defined as the number of true positives divided by the number of
    all detected boxes and the recall is defined as the number of true positives divided by the number of all ground
    boxes.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~List`): A list consisting of dictionaries each containing the key-values
      (each dictionary corresponds to a single image). Parameters that should be provided per dict

        - ``boxes`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes, 4)`` containing ``num_boxes``
          detection boxes of the format specified in the constructor.
          By default, this method expects ``(xmin, ymin, xmax, ymax)`` in absolute image coordinates, but can be changed
          using the ``box_format`` parameter. Only required when `iou_type="bbox"`.
        - ``scores`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes)`` containing detection scores for the
          boxes.
        - ``labels`` (:class:`~torch.Tensor`): integer tensor of shape ``(num_boxes)`` containing 0-indexed detection
          classes for the boxes.
        - ``masks`` (:class:`~torch.Tensor`): boolean tensor of shape ``(num_boxes, image_height, image_width)``
          containing boolean masks. Only required when `iou_type="segm"`.

    - ``target`` (:class:`~List`): A list consisting of dictionaries each containing the key-values
      (each dictionary corresponds to a single image). Parameters that should be provided per dict:

        - ``boxes`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes, 4)`` containing ``num_boxes`` ground
          truth boxes of the format specified in the constructor. only required when `iou_type="bbox"`.
          By default, this method expects ``(xmin, ymin, xmax, ymax)`` in absolute image coordinates.
        - ``labels`` (:class:`~torch.Tensor`): integer tensor of shape ``(num_boxes)`` containing 0-indexed ground truth
          classes for the boxes.
        - ``masks`` (:class:`~torch.Tensor`): boolean tensor of shape ``(num_boxes, image_height, image_width)``
          containing boolean masks. Only required when `iou_type="segm"`.
        - ``iscrowd`` (:class:`~torch.Tensor`): integer tensor of shape ``(num_boxes)`` containing 0/1 values indicating
          whether the bounding box/masks indicate a crowd of objects. Value is optional, and if not provided it will
          automatically be set to 0.
        - ``area`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes)`` containing the area of the object.
          Value is optional, and if not provided will be automatically calculated based on the bounding box/masks
          provided. Only affects which samples contribute to the `map_small`, `map_medium`, `map_large` values

    As output of ``forward`` and ``compute`` the metric returns the following output:

    - ``map_dict``: A dictionary containing the following key-values:

        - map: (:class:`~torch.Tensor`), global mean average precision
        - map_small: (:class:`~torch.Tensor`), mean average precision for small objects
        - map_medium:(:class:`~torch.Tensor`), mean average precision for medium objects
        - map_large: (:class:`~torch.Tensor`), mean average precision for large objects
        - mar_1: (:class:`~torch.Tensor`), mean average recall for 1 detection per image
        - mar_10: (:class:`~torch.Tensor`), mean average recall for 10 detections per image
        - mar_100: (:class:`~torch.Tensor`), mean average recall for 100 detections per image
        - mar_small: (:class:`~torch.Tensor`), mean average recall for small objects
        - mar_medium: (:class:`~torch.Tensor`), mean average recall for medium objects
        - mar_large: (:class:`~torch.Tensor`), mean average recall for large objects
        - map_50: (:class:`~torch.Tensor`) (-1 if 0.5 not in the list of iou thresholds), mean average precision at
          IoU=0.50
        - map_75: (:class:`~torch.Tensor`) (-1 if 0.75 not in the list of iou thresholds), mean average precision at
          IoU=0.75
        - map_per_class: (:class:`~torch.Tensor`) (-1 if class metrics are disabled), mean average precision per
          observed class
        - mar_100_per_class: (:class:`~torch.Tensor`) (-1 if class metrics are disabled), mean average recall for 100
          detections per image per observed class
        - classes (:class:`~torch.Tensor`), list of all observed classes

    For an example on how to use this metric check the `torchmetrics mAP example`_.

    .. note::
        ``map`` score is calculated with @[ IoU=self.iou_thresholds | area=all | max_dets=max_detection_thresholds ].
        Caution: If the initialization parameters are changed, dictionary keys for mAR can change as well.

    .. note::
        This metric utilizes the official `pycocotools` implementation as its backend. This means that the metric
        requires you to have `pycocotools` installed. In addition we require `torchvision` version 0.8.0 or newer.
        Please install with ``pip install torchmetrics[detection]``.

    Args:
        box_format:
            Input format of given boxes. Supported formats are:

                - 'xyxy': boxes are represented via corners, x1, y1 being top left and x2, y2 being bottom right.
                - 'xywh' : boxes are represented via corner, width and height, x1, y2 being top left, w, h being
                  width and height. This is the default format used by pycoco and all input formats will be converted
                  to this.
                - 'cxcywh': boxes are represented via centre, width and height, cx, cy being center of box, w, h being
                  width and height.

        iou_type:
            Type of input (either masks or bounding-boxes) used for computing IOU. Supported IOU types are
            ``"bbox"`` or ``"segm"`` or both as a tuple.
        iou_thresholds:
            IoU thresholds for evaluation. If set to ``None`` it corresponds to the stepped range ``[0.5,...,0.95]``
            with step ``0.05``. Else provide a list of floats.
        rec_thresholds:
            Recall thresholds for evaluation. If set to ``None`` it corresponds to the stepped range ``[0,...,1]``
            with step ``0.01``. Else provide a list of floats.
        max_detection_thresholds:
            Thresholds on max detections per image. If set to `None` will use thresholds ``[1, 10, 100]``.
            Else, please provide a list of ints.
        class_metrics:
            Option to enable per-class metrics for mAP and mAR_100. Has a performance impact that scales linearly with
            the number of classes in the dataset.
        extended_summary:
            Option to enable extended summary with additional metrics including IOU, precision and recall. The output
            dictionary will contain the following extra key-values:

                - ``ious``: a dictionary containing the IoU values for every image/class combination e.g.
                  ``ious[(0,0)]`` would contain the IoU for image 0 and class 0. Each value is a tensor with shape
                  ``(n,m)`` where ``n`` is the number of detections and ``m`` is the number of ground truth boxes for
                  that image/class combination.
                - ``precision``: a tensor of shape ``(TxRxKxAxM)`` containing the precision values. Here ``T`` is the
                  number of IoU thresholds, ``R`` is the number of recall thresholds, ``K`` is the number of classes,
                  ``A`` is the number of areas and ``M`` is the number of max detections per image.
                - ``recall``: a tensor of shape ``(TxKxAxM)`` containing the recall values. Here ``T`` is the number of
                  IoU thresholds, ``K`` is the number of classes, ``A`` is the number of areas and ``M`` is the number
                  of max detections per image.

        average:
            Method for averaging scores over labels. Choose between "``macro``"" and "``micro``". Default is "macro"

        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ModuleNotFoundError:
            If ``pycocotools`` is not installed
        ModuleNotFoundError:
            If ``torchvision`` is not installed or version installed is lower than 0.8.0
        ValueError:
            If ``box_format`` is not one of ``"xyxy"``, ``"xywh"`` or ``"cxcywh"``
        ValueError:
            If ``iou_type`` is not one of ``"bbox"`` or ``"segm"``
        ValueError:
            If ``iou_thresholds`` is not None or a list of floats
        ValueError:
            If ``rec_thresholds`` is not None or a list of floats
        ValueError:
            If ``max_detection_thresholds`` is not None or a list of ints
        ValueError:
            If ``class_metrics`` is not a boolean

    Example::

        Basic example for when `iou_type="bbox"`. In this case the ``boxes`` key is required in the input dictionaries,
        in addition to the ``scores`` and ``labels`` keys.

        >>> from torch import tensor
        >>> from torchmetrics.detection import MeanAveragePrecision
        >>> preds = [
        ...   dict(
        ...     boxes=tensor([[258.0, 41.0, 606.0, 285.0]]),
        ...     scores=tensor([0.536]),
        ...     labels=tensor([0]),
        ...   )
        ... ]
        >>> target = [
        ...   dict(
        ...     boxes=tensor([[214.0, 41.0, 562.0, 285.0]]),
        ...     labels=tensor([0]),
        ...   )
        ... ]
        >>> metric = MeanAveragePrecision(iou_type="bbox")
        >>> metric.update(preds, target)
        >>> from pprint import pprint
        >>> pprint(metric.compute())
        {'classes': tensor(0, dtype=torch.int32),
         'map': tensor(0.6000),
         'map_50': tensor(1.),
         'map_75': tensor(1.),
         'map_large': tensor(0.6000),
         'map_medium': tensor(-1.),
         'map_per_class': tensor(-1.),
         'map_small': tensor(-1.),
         'mar_1': tensor(0.6000),
         'mar_10': tensor(0.6000),
         'mar_100': tensor(0.6000),
         'mar_100_per_class': tensor(-1.),
         'mar_large': tensor(0.6000),
         'mar_medium': tensor(-1.),
         'mar_small': tensor(-1.)}

    Example::

        Basic example for when `iou_type="segm"`. In this case the ``masks`` key is required in the input dictionaries,
        in addition to the ``scores`` and ``labels`` keys.

        >>> from torch import tensor
        >>> from torchmetrics.detection import MeanAveragePrecision
        >>> mask_pred = [
        ...   [0, 0, 0, 0, 0],
        ...   [0, 0, 1, 1, 0],
        ...   [0, 0, 1, 1, 0],
        ...   [0, 0, 0, 0, 0],
        ...   [0, 0, 0, 0, 0],
        ... ]
        >>> mask_tgt = [
        ...   [0, 0, 0, 0, 0],
        ...   [0, 0, 1, 0, 0],
        ...   [0, 0, 1, 1, 0],
        ...   [0, 0, 1, 0, 0],
        ...   [0, 0, 0, 0, 0],
        ... ]
        >>> preds = [
        ...   dict(
        ...     masks=tensor([mask_pred], dtype=torch.bool),
        ...     scores=tensor([0.536]),
        ...     labels=tensor([0]),
        ...   )
        ... ]
        >>> target = [
        ...   dict(
        ...     masks=tensor([mask_tgt], dtype=torch.bool),
        ...     labels=tensor([0]),
        ...   )
        ... ]
        >>> metric = MeanAveragePrecision(iou_type="segm")
        >>> metric.update(preds, target)
        >>> from pprint import pprint
        >>> pprint(metric.compute())
        {'classes': tensor(0, dtype=torch.int32),
         'map': tensor(0.2000),
         'map_50': tensor(1.),
         'map_75': tensor(0.),
         'map_large': tensor(-1.),
         'map_medium': tensor(-1.),
         'map_per_class': tensor(-1.),
         'map_small': tensor(0.2000),
         'mar_1': tensor(0.2000),
         'mar_10': tensor(0.2000),
         'mar_100': tensor(0.2000),
         'mar_100_per_class': tensor(-1.),
         'mar_large': tensor(-1.),
         'mar_medium': tensor(-1.),
         'mar_small': tensor(0.2000)}

    Fis_differentiableThigher_is_betterfull_state_update        plot_lower_bound      ?plot_upper_bounddetection_boxdetection_maskdetection_scoresdetection_labelsgroundtruth_boxgroundtruth_maskgroundtruth_labelsgroundtruth_crowdsgroundtruth_areawarn_on_many_detectionsxyxybboxNmacror0   xywhZcxcywh)r1   segmr2   micro)

box_formatiou_typeiou_thresholdsrec_thresholdsmax_detection_thresholdsclass_metricsextended_summaryaveragekwargsreturnc	                    s  t  jf i |	 tstdts*tdd}
||
vrJtd|
 d| || _t|| _|d urzt	|t
sztd| |ptddtd	d
  | _|d urt	|t
std| |ptddtdd
  | _|d urt	|t
std| ttj|pg dtjd\}}| | _t	|ts<td|| _t	|tsVtd|| _|dvrttd| || _| jdg d d | jdg d d | jdg d d | jdg d d | jdg d d | jdg d d | jdg d d | jdg d d | jdg d d d S ) Nz`MAP` metric requires that `pycocotools` installed. Please install with `pip install pycocotools` or `pip install torchmetrics[detection]`z`MeanAveragePrecision` metric requires that `torchvision` version 0.8.0 or newer is installed. Please install with `pip install torchvision>=0.8` or `pip install torchmetrics[detection]`.r3   z,Expected argument `box_format` to be one of z	 but got zSExpected argument `iou_thresholds` to either be `None` or a list of floats but got g      ?gffffff?g!@   zSExpected argument `rec_thresholds` to either be `None` or a list of floats but got r"   r$   g      Y@z[Expected argument `max_detection_thresholds` to either be `None` or a list of ints but got )rB   
   d   Zdtypez1Expected argument `class_metrics` to be a booleanz4Expected argument `extended_summary` to be a booleanr6   zDExpected argument `average` to be one of ('macro', 'micro') but got r&   )defaultZdist_reduce_fxr'   r(   r)   r*   r+   r,   r-   r.   )super__init__r   ModuleNotFoundErrorr   
ValueErrorr8   r   r9   
isinstancelisttorchZlinspaceroundtolistr:   r;   sorttensorintr<   boolr=   r>   r?   Z	add_state)selfr8   r9   r:   r;   r<   r=   r>   r?   r@   Zallowed_box_formatsZmax_det_thr_	__class__ g/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/detection/mean_ap.pyrH   F  sd    
  $

zMeanAveragePrecision.__init__)predstargetrA   c              
   C   s  t ||| jd |D ]`}| j|| jd\}}|dur@| j| |durT| j| | j|d  | j|d  q|D ]}| |\}}|dur| j	| |dur| j
| | j|d  | j|dt|d  | j|dt|d  qzdS )aP  Update metric state.

        Raises:
            ValueError:
                If ``preds`` is not of type (:class:`~List[Dict[str, Tensor]]`)
            ValueError:
                If ``target`` is not of type ``List[Dict[str, Tensor]]``
            ValueError:
                If ``preds`` and ``target`` are not of the same length
            ValueError:
                If any of ``preds.boxes``, ``preds.scores`` and ``preds.labels`` are not of the same length
            ValueError:
                If any of ``target.boxes`` and ``target.labels`` are not of the same length
            ValueError:
                If any box is not type float and of length 4
            ValueError:
                If any class is not type int and of length 1
            ValueError:
                If any score is not type float and of length 1

        )r9   )warnNlabelsscoresiscrowdarea)r   r9   _get_safe_item_valuesr/   r&   appendr'   r)   r(   r*   r+   r,   r-   getrM   
zeros_liker.   )rT   rZ   r[   itemZbbox_detectionZmask_detectionZbbox_groundtruthZmask_groundtruthrX   rX   rY   update  s$    zMeanAveragePrecision.update)rA   c                 C   s   | j | jd\}}i }tt  | jD ]}t| jdkrFdn| d}t| jdkr|jd D ]}|d|  |d< qht	|||d}t
j| jt
jd	|j_t
j| jt
jd	|j_| j|j_|  |  |  |j}|| j||d
 i }	| jrL| dt|jt
jdd | dt|j d | dt|j d i}	||	 | j!r|| jdkr| j dd\}}t	|||d}t
j| jt
jd	|j_t
j| jt
jd	|j_| j|j_g }
g }| " D ]}|g|j_#tt . |  |  |  |j}W d   n1 s 0    Y  |
$t|d g |$t|d g qtj|
tj%d	}tj|tj%d	}n$tjdgtj%d	}tjdgtj%d	}t| jdkrdn| d}|| d|| d|i q.W d   n1 s0    Y  |dtj| " tj&d	i |S )zComputes the metric.)r?   rB    rU   annotationsZarea_r`   )ZiouTyperE   )prefixiousc                 S   s   t j| t jdS )NrE   rM   rQ   float32xrX   rX   rY   <lambda>      z.MeanAveragePrecision.compute.<locals>.<lambda>Z	precisionZrecallr7   r2   Nr      Zmap_per_classZmar_100_per_classclasses)'_get_coco_datasetsr?   
contextlibredirect_stdoutioStringIOr9   lendatasetr   nparrayr:   float64paramsZiouThrsr;   ZrecThrsr<   ZmaxDetsevaluate
accumulateZ	summarizestatsrf   _coco_stats_to_tensor_dictr>   r
   rj   ZndarrayrM   rQ   evalr=   _get_classesZcatIdsrb   rl   int32)rT   
coco_predscoco_targetZresult_dictZi_typeri   annoZ	coco_evalr   summaryZmap_per_class_listZmar_100_per_class_listZclass_idZclass_statsZmap_per_class_valuesZmar_100_per_class_valuesrX   rX   rY   compute  sp    




&

&zMeanAveragePrecision.compute)r?   rA   c                 C   s  |dkr.t | jtdd }t | jtdd }n| j}| j}t t  }}| j|t| jdkrb| jndt| jdkrx| jnd| j	| j
d|_| j|t| jdkr| jndt| jdkr| jnd| jd|_tt   |  |  W d   n1 s0    Y  ||fS )	z=Returns the coco datasets for the target and the predictions.r7   c                 S   s
   t | S NrM   rd   rm   rX   rX   rY   ro     rp   z9MeanAveragePrecision._get_coco_datasets.<locals>.<lambda>c                 S   s
   t | S r   r   rm   rX   rX   rY   ro     rp   r   Nr]   boxesmaskscrowdsr`   )r]   r   r   r^   )r
   r,   r   r)   r   _get_coco_formatry   r*   r+   r-   r.   rz   r&   r'   r(   ru   rv   rw   rx   ZcreateIndex)rT   r?   r,   r)   r   r   rX   rX   rY   rt     s.    &z'MeanAveragePrecision._get_coco_datasets)r   ri   rA   c                 C   sT  | dt j| d gt jd| dt j| d gt jd| dt j| d gt jd| dt j| d	 gt jd| d
t j| d gt jd| dt j| d gt jd| dt j| d gt jd| dt j| d gt jd| dt j| d gt jd| dt j| d gt jd| dt j| d gt jd| dt j| d gt jdiS )z;Converts the output of COCOeval.stats to a dict of tensors.mapr   rE   Zmap_50rB   Zmap_75   Z	map_small   Z
map_medium   Z	map_large   Zmar_1   Zmar_10   Zmar_100rq   Z	mar_small	   Z
mar_mediumrC   Z	mar_large   rk   )r   ri   rX   rX   rY   r   '  s    z/MeanAveragePrecision._coco_stats_to_tensor_dict)r   r   r9   rA   c                 C   s  t |}tt " t|}|| }W d   n1 s>0    Y  |jd }|jd }i }|D ]}|d |vrg g g d||d < d|v rg ||d  d< d|v rg ||d  d< d|v r||d  d |d  d|v r||d  d |	| ||d  d	 |d
  ||d  d |d  ||d  d |d  qdi }	|D ]}
|
d |	vrg g d|	|
d < d|v rg |	|
d  d< d|v rg |	|
d  d< d|v r|	|
d  d |
d  d|v r|	|
d  d |	|
 |	|
d  d |
d  |	|
d  d	 |
d
  qV|D ]J}||	vr4g g d|	|< d|v rfg |	| d< d|v r4g |	| d< q4g g  }}|D ]>}t
j|	| d t
jdt
j|	| d	 t
jdd}d|v rt
jt|	| d t
jd|d< d|v rt
jt|	| d t
jd|d< || t
j|| d	 t
jdt
j|| d t
jdt
j|| d t
jdd}d|v rt
j|| d t
jd|d< d|v rt
jt|| d t
jd|d< || q||fS )am  Utility function for converting .json coco format files to the input format of this metric.

        The function accepts a file for the predictions and a file for the target in coco format and converts them to
        a list of dictionaries containing the boxes, labels and scores in the input format of this metric.

        Args:
            coco_preds: Path to the json file containing the predictions in coco format
            coco_target: Path to the json file containing the targets in coco format
            iou_type: Type of input, either `bbox` for bounding boxes or `segm` for segmentation masks

        Returns:
            A tuple containing the predictions and targets in the input format of this metric. Each element of the
            tuple is a list of dictionaries containing the boxes, labels and scores.

        Example:
            >>> # File formats are defined at https://cocodataset.org/#format-data
            >>> # Example files can be found at
            >>> # https://github.com/cocodataset/cocoapi/tree/master/results
            >>> from torchmetrics.detection import MeanAveragePrecision
            >>> preds, target = MeanAveragePrecision.coco_to_tm(
            ...   "instances_val2014_fakebbox100_results.json.json",
            ...   "val2014_fake_eval_res.txt.json"
            ...   iou_type="bbox"
            ... )  # doctest: +SKIP

        Nrh   image_id)r]   r_   r`   r1   r   r5   r   r]   category_idr_   r`   )r^   r]   r^   scorerE   )r   ru   rv   rw   rx   r   ZloadResrz   rb   Z	annToMaskrM   rQ   rl   r   r{   r|   Zuint8)r   r   r9   gtdtZ
gt_datasetZ
dt_datasetr[   trZ   pkZbatched_predsZbatched_targetkeyZbpZbtrX   rX   rY   
coco_to_tm9  s     (











"
"


"r   tm_map_input)namerA   c                 C   s   | j | j| j| j| j| jd}| j | j| j| jd}t	j
|d dd}t	j
|dd}t| dd}|| W d   n1 s0    Y  t| d	d}|| W d   n1 s0    Y  dS )
a  Utility function for converting the input for this metric to coco format and saving it to a json file.

        This function should be used after calling `.update(...)` or `.forward(...)` on all data that should be written
        to the file, as the input is then internally cached. The function then converts to information to coco format
        a writes it to json files.

        Args:
            name: Name of the output file, which will be appended with "_preds.json" and "_target.json"

        Example:
            >>> from torch import tensor
            >>> from torchmetrics.detection import MeanAveragePrecision
            >>> preds = [
            ...   dict(
            ...     boxes=tensor([[258.0, 41.0, 606.0, 285.0]]),
            ...     scores=tensor([0.536]),
            ...     labels=tensor([0]),
            ...   )
            ... ]
            >>> target = [
            ...   dict(
            ...     boxes=tensor([[214.0, 41.0, 562.0, 285.0]]),
            ...     labels=tensor([0]),
            ...   )
            ... ]
            >>> metric = MeanAveragePrecision()
            >>> metric.update(preds, target)
            >>> metric.tm_to_coco("tm_map_input")  # doctest: +SKIP

        r   )r]   r   r   rh   r   )indentz_preds.jsonwNz_target.json)r   r,   r*   r+   r-   r.   r)   r&   r'   jsondumpsopenwrite)rT   r   Ztarget_datasetZpreds_datasetZ
preds_jsonZtarget_jsonfrX   rX   rY   
tm_to_coco  s     (r   )re   r\   rA   c                 C   s   ddg}d| j v rBt|d }| dkr:t|| jdd}||d< d| j v rg }|d   D ].}tt	
|}|t|d	 |d
 f q`t||d< |d durt|d | jd ks|d durt|d | jd krt| jd  |S )aV  Convert and return the boxes or masks from the item depending on the iou_type.

        Args:
            item: input dictionary containing the boxes or masks
            warn: whether to warn if the number of boxes or masks exceeds the max_detection_thresholds

        Returns:
            boxes or masks depending on the iou_type

        Nr1   r   r   r4   )Zin_fmtZout_fmtr5   r   sizecountsrB   rr   )r9   r   Znumelr   r8   cpunumpy
mask_utilsencoder{   Zasfortranarrayrb   tuplery   r<   _warning_on_too_many_detections)rT   re   r\   outputr   r   iZrlerX   rX   rY   ra     s&    

"
z*MeanAveragePrecision._get_safe_item_valuesc                 C   s>   t | jdkst | jdkr:t| j| j    S g S )zIReturn a list of unique classes found in ground truth and detection data.r   )ry   r)   r,   rM   catuniquer   rO   )rT   rX   rX   rY   r     s    z!MeanAveragePrecision._get_classes)r]   r   r   r^   r   r`   rA   c              
   C   s  g }g }d}	t |D ]\}
}|dur:||
 }|  }|dur`||
 }t|dkr`|du r`q|  }|d|
i d| jv rt|dkr|d d d |d d d  |d d< |d d< t |D ]\}}|dur|| }|durt|dkr|| }|d |d d	}d
| jv rPt|dkrPtd|
 d| dt| dt|tkr~td|
 d| dt| dd}d}|dur||
 |   dkr||
 |   }nPd| jv rt	
|n|d |d  }t| jdkr|d |d  }t	
|}|	|
|||dur6||
 |   ndd}|durX||d< ||d< |durj||d
< |dur|||d< |dur||
 |   }t|tkrtd|
 d| dt| d||d< || |	d7 }	qqdd |  D }|||dS )zTransforms and returns all cached targets or predictions in COCO format.

        Format is defined at
        https://cocodataset.org/#format-data

        rB   Nr   idr5   rr   heightwidth)r   r   r1   r   zInvalid input box of sample z
, element z (expected 4 values, got )zInvalid input class of sample z+ (expected value of type integer, got type r   r   )r   r   r`   r   r_   Z	area_bboxZ	area_segmZsegmentationzInvalid input score of sample z) (expected value of type float, got type r   c                 S   s   g | ]}|t |d qS ))r   r   )str).0r   rX   rX   rY   
<listcomp>V  rp   z9MeanAveragePrecision._get_coco_format.<locals>.<listcomp>)imagesrh   
categories)	enumerater   rO   ry   rb   r9   rJ   typerR   r   r`   floatr   )rT   r]   r   r   r^   r   r`   r   rh   Zannotation_idr   Zimage_labelsZimage_boxesZimage_masksr   Zimage_labelZ	image_boxZ
image_maskZarea_stat_boxZarea_stat_maskZ	area_stat
annotationr   rs   rX   rX   rY   r     s    2$&
 




z%MeanAveragePrecision._get_coco_format)valaxrA   c                 C   s   |  ||S )a  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure object and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> from torch import tensor
            >>> from torchmetrics.detection.mean_ap import MeanAveragePrecision
            >>> preds = [dict(
            ...     boxes=tensor([[258.0, 41.0, 606.0, 285.0]]),
            ...     scores=tensor([0.536]),
            ...     labels=tensor([0]),
            ... )]
            >>> target = [dict(
            ...     boxes=tensor([[214.0, 41.0, 562.0, 285.0]]),
            ...     labels=tensor([0]),
            ... )]
            >>> metric = MeanAveragePrecision()
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.detection.mean_ap import MeanAveragePrecision
            >>> preds = lambda: [dict(
            ...     boxes=torch.tensor([[258.0, 41.0, 606.0, 285.0]]) + torch.randint(10, (1,4)),
            ...     scores=torch.tensor([0.536]) + 0.1*torch.rand(1),
            ...     labels=torch.tensor([0]),
            ... )]
            >>> target = [dict(
            ...     boxes=torch.tensor([[214.0, 41.0, 562.0, 285.0]]),
            ...     labels=torch.tensor([0]),
            ... )]
            >>> metric = MeanAveragePrecision()
            >>> vals = []
            >>> for _ in range(20):
            ...     vals.append(metric(preds(), target))
            >>> fig_, ax_ = metric.plot(vals)

        )Z_plot)rT   r   r   rX   rX   rY   plotY  s    9r   )fnrA   c                    s   t  j|ddS )zCustom apply function.

        Excludes the detections and groundtruths from the casting when the iou_type is set to `segm` as the state is
        no longer a tensor but a tuple.

        )r'   r+   )Zexclude_state)rG   _apply)rT   r   rV   rX   rY   r     s    zMeanAveragePrecision._apply)dist_sync_fnprocess_grouprA   c                    s>   t  j||d d| jv r:| | j|| _| | j|| _dS )zCustom sync function.

        For the iou_type `segm` the detections and groundtruths are no longer tensors but tuples. Therefore, we need
        to gather the list of tuples and then convert it back to a list of tuples.

        )r   r   r5   N)rG   
_sync_distr9   _gather_tuple_listr'   r+   )rT   r   r   rV   rX   rY   r     s    
zMeanAveragePrecision._sync_dist)list_to_gatherr   rA   c                    sZ   t j|dt j|d dd tD  t j | |d  fddtt d D S )a*  Gather a list of tuples over multiple devices.

        Args:
            list_to_gather: input list of tuples that should be gathered across devices
            process_group: process group to gather the list of tuples

        Returns:
            list of tuples gathered across devices

        )groupc                 S   s   g | ]}d qS r   rX   )r   rU   rX   rX   rY   r     rp   z;MeanAveragePrecision._gather_tuple_list.<locals>.<listcomp>c                    s&   g | ]}t D ]} | | qqS rX   )range)r   idxZrankZlist_gatheredZ
world_sizerX   rY   r     rp   r   )distZget_world_sizeZbarrierr   Zall_gather_objectry   )r   r   rX   r   rY   r     s
    z'MeanAveragePrecision._gather_tuple_list)r0   r1   NNNFFr2   )r1   )r   )F)NNNNN)NN)NN)N)0__name__
__module____qualname____doc__r   rS   __annotations__r    r   r!   r#   r   r%   r   r   r/   r   r	   r   r   rR   r   rH   r   rf   dictr   r   rt   staticmethodr   r   r   ra   r   rM   r   r   r   r   r   r   nnModuler   r   r   __classcell__rX   rX   rV   rY   r   C   s   
 q        


J*+L   "l4 	     \ (?	 r   )limitrA   c                 C   s   t d|  dt d S )NzEncountered more than aY   detections in a single image. This means that certain detections with the lowest scores will be ignored, that may have an undesirable impact on performance. Please consider adjusting the `max_detection_threshold` to suit your use case. To disable this warning, set attribute class `warn_on_many_detections=False`, after initializing the metric.)r   UserWarning)r   rX   rX   rY   r     s    
r   )2ru   rw   r   typingr   r   r   r   r   r   r   r	   r   r{   rM   Zlightning_utilitiesr
   r   r   r   Ztyping_extensionsr   Ztorchmetrics.detection.helpersr   r   r   Ztorchmetrics.metricr   Ztorchmetrics.utilitiesr   Ztorchmetrics.utilities.importsr   r   r   Ztorchmetrics.utilities.plotr   r   Z__doctest_skip__Ztorchvision.opsr   Zpycocotools.maskmaskr   Zpycocotools.cocor   Zpycocotools.cocoevalr   r   rR   r   rX   rX   rX   rY   <module>   sH   (       