§
    >²¸j‘u  ã                  ót  — d dl mZ d dlZd dlmZ d dlmZ d dlmZmZm	Z	 d dl
Zd dlmZ d dlmZ d dlmZmZ d dlmZmZmZmZ d d	lmZ d d
lmZmZmZ d dlmZm Z  d dl!m"Z"m#Z# erd dl$m%Z% e&e'ef         Z(dHd„Z)dId„Z*dJd„Z+dKd„Z,dLd„Z-	 dMdNd%„Z.	 	 	 dOdPd2„Z/dQd5„Z0	 	 	 dRdSd;„Z1dTd>„Z2dUdB„Z3	 	 	 	 	 	 dVdWdG„Z4dS )Xé    )ÚannotationsN)Údatetime)ÚPath)ÚTYPE_CHECKINGÚAnyÚcast)Útqdm)ÚAREA_DATA_FIELDÚCOCO_RAW_SEGMENTATION)Ú_image_file_resolution_whÚapproximate_mask_with_polygonsÚcheck_no_basename_collisionsÚmap_detections_class_id)Ú
Detections)Úmask_to_rleÚpolygon_to_maskÚrle_to_mask)Úcontains_holesÚcontains_multiple_segments)Úread_json_fileÚsave_json_file)ÚDetectionDatasetÚcoco_categoriesúlist[CocoDict]Úreturnú	list[str]c                ó:   — d„ t          | d„ ¬¦  «        D ¦   «         S )Nc                ó   — g | ]
}|d          ‘ŒS )Úname© ©Ú.0Úcategorys     úp/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/supervision/dataset/formats/coco.pyú
<listcomp>z.coco_categories_to_classes.<locals>.<listcomp>#   s-   € ð ð ð àð 	�Ôðð ð ó    c                ó   — | d         S )NÚidr    )r#   s    r$   ú<lambda>z,coco_categories_to_classes.<locals>.<lambda>%   s
   € ÀXÈdÄ^€ r&   )Úkey)Úsorted©r   s    r$   Úcoco_categories_to_classesr-   "   s4   € ðð å˜Ð4SÐ4SÐTÑTÔTðñ ô ð r&   Útarget_classesúdict[int, int]c                óR   ‡— d„ | D ¦   «         Šˆfd„t          |¦  «        D ¦   «         S )Nc                ó,   — i | ]}|d          |d         “ŒS )r   r(   r    r!   s     r$   ú
<dictcomp>z2build_coco_class_index_mapping.<locals>.<dictcomp>,   s0   € ð ð ð Ø-5ˆ�Ô˜( 4œ.ðð ð r&   c                ó(   •— i | ]\  }}‰|         |“ŒS r    r    )r"   Útarget_class_indexÚtarget_class_nameÚsource_class_to_indexs      €r$   r2   z2build_coco_class_index_mapping.<locals>.<dictcomp>/   s8   ø€ ð ð ð á1ÐÐ 1ð 	Ð/Ô0Ð2Dðð ð r&   ©Ú	enumerate)r   r.   r6   s     @r$   Úbuild_coco_class_index_mappingr9   )   sU   ø€ ðð Ø9Hðñ ô Ððð ð ð å5>¸~Ñ5NÔ5Nðñ ô ð r&   Úclassesc                ó4   — d„ t          | ¦  «        D ¦   «         S )a¼  Convert a list of class names to COCO ``categories`` entries.

    Category ids are emitted 1-indexed to comply with the COCO specification
    and tools such as CVAT, which require ``category_id`` values to start at
    ``1``. The id assigned to the class at position ``class_index`` is
    ``class_index + 1``, keeping it consistent with the ``category_id`` written
    by [`detections_to_coco_annotations`](#detections_to_coco_annotations).

    Args:
        classes: Class names ordered by their internal (0-indexed) class id.

    Returns:
        A list of COCO category dictionaries with 1-indexed ``id`` values.

    Example:
        ```pycon
        >>> from supervision.dataset.formats.coco import classes_to_coco_categories
        >>> classes_to_coco_categories(classes=["cat", "dog"])
        [{'id': 1, 'name': 'cat', 'supercategory': 'common-objects'},
         {'id': 2, 'name': 'dog', 'supercategory': 'common-objects'}]

        ```
    c                ó&   — g | ]\  }}|d z   |ddœ‘ŒS )é   zcommon-objects)r(   r   Úsupercategoryr    )r"   Úclass_indexÚ
class_names      r$   r%   z.classes_to_coco_categories.<locals>.<listcomp>M   sB   € ð ð ð ñ $ˆK˜ð	  ‘/ØØ-ð	
ð 	
ðð ð r&   r7   ©r:   s    r$   Úclasses_to_coco_categoriesrB   5   s-   € ð0ð õ (1°Ñ'9Ô'9ðñ ô ð r&   Úcoco_annotationsúdict[int, list[CocoDict]]c                ól   — i }| D ].}|d         }||vrg ||<   ||                               |¦  «         Œ/|S )NÚimage_id)Úappend)rC   r   Ú
annotationrF   s       r$   Ú"group_coco_annotations_by_image_idrI   W   sY   € ð .0€KØ&ð 1ð 1ˆ
Ø˜jÔ)ˆØ˜;Ð&Ð&Ø$&ˆK˜Ñ!Ø�HÔ×$Ò$ ZÑ0Ô0Ð0Ð0ØÐr&   Úimage_annotationsÚresolution_whútuple[int, int]únpt.NDArray[np.bool_]c                óœ  — |d         |d         }}t          j        ||ft          ¬¦  «        }g }| D �]}|                     d¦  «        }|s(|                     |                     ¦   «         ¦  «         ŒBt          |t          ¦  «        r…d|vrVt          j	        d|                     dd¦  «        › d	�d
¬¦  «         |                     |                     ¦   «         ¦  «         Œ±|                     t          |d         |¬¦  «        ¦  «         ŒÜt          |t          ¦  «        s)|                     |                     ¦   «         ¦  «         �Œt          |d         t          ¦  «        r|n|g}|                     ¦   «         }	|D �]}
t          j        t          j        |
t           j        ¬¦  «        d¦  «        }|j        dk    r.t          j	        d|                     d¦  «        › d�d
¬¦  «         Œot          j        |¦  «                             ¦   «         s&t%          d|                     d¦  «        › d�¦  «        ‚t          j        |¦  «                             t           j        ¦  «        }|	t-          ||¬¦  «                             t          ¦  «        z  }	�Œ|                     |	¦  «         �Œ�t          j        |t          ¬¦  «        S )zKRasterise each annotation's RLE or polygon segmentation into one bool mask.r=   r   ©ÚdtypeÚsegmentationÚcountszSkipping annotation r(   Ú?zG: segmentation is a dict but missing 'counts' key (expected RLE format)é   ©Ú
stacklevel)ÚrlerK   )éÿÿÿÿrT   zISkipping empty polygon while loading COCO segmentation for annotation id=ú.z,COCO polygon segmentation for annotation id=z* has a vertex that is not a finite number.)ÚpolygonrK   )ÚnpÚzerosÚboolÚgetrG   ÚcopyÚ
isinstanceÚdictÚwarningsÚwarnr   ÚlistÚreshapeÚasarrayÚfloat64ÚsizeÚisfiniteÚallÚ
ValueErrorÚroundÚastypeÚint32r   )rJ   rK   ÚheightÚwidthÚ
empty_maskÚmasksÚimage_annotationrQ   ÚpolygonsÚobject_maskrZ   ÚverticesÚpolygon_arrays                r$   Úcoco_annotations_to_masksrx   c   sî  € ð " !Ô$ m°AÔ&6ˆE€FÝ(*¬°&¸%°ÍÐ(MÑ(MÔ(M€JØ€Eà-ð 6"ñ 6"ÐØ'×+Ò+¨NÑ;Ô;ˆØð 	ð �LŠL˜ŸšÑ*Ô*Ñ+Ô+Ð+Øå�l¥DÑ)Ô)ð 	Ø˜|Ð+Ð+Ý”ðAØ'×+Ò+¨D°#Ñ6Ô6ðAð Að Að  !ð	ñ ô ð ð —’˜ZŸ_š_Ñ.Ô.Ñ/Ô/Ð/ØØ�LŠLÝ ¨XÔ 6ÀmÐTÑTÔTñô ð ð å˜,­Ñ-Ô-ð 	Ø�LŠL˜ŸšÑ*Ô*Ñ+Ô+Ð+ÙÝ#-¨l¸1¬o½tÑ#DÔ#DÐX�<�<È<È.ˆà —o’oÑ'Ô'ˆØð 	ñ 	ˆGÝ”z¥"¤*¨W½B¼JÐ"GÑ"GÔ"GÈÑQÔQˆHØŒ} Ò!Ð!Ý”ðCØ%5×%9Ò%9¸$Ñ%?Ô%?ðCð Cð Cà ðñ ô ð ð
 Ý”;˜xÑ(Ô(×,Ò,Ñ.Ô.ð Ý ð%Ø*×.Ò.¨tÑ4Ô4ð%ð %ð %ñô ð õ 46´8¸HÑ3EÔ3E×3LÒ3LÍRÌXÑ3VÔ3VˆMð �?Ø%°]ðñ ô çŠf•T‰lŒlñˆK‰Kð 	�Š�[Ñ!Ô!Ð!Ñ!åŒ:�e¥4Ð(Ñ(Ô(Ð(r&   TÚ
with_masksr]   Úuse_iscrowdr   c                óÚ  — | st          j        ¦   «         S d„ | D ¦   «         }d„ | D ¦   «         }t          j        |t          j        ¬¦  «        }|dd…dd…fxx         |dd…dd…f         z  cc<   i }|r×d„ | D ¦   «         }g }	| D ]ƒ}
d	|
v r|	                     |
d	         ¦  «         Œ"|r/t          |
¦  «        r |	                     t          j        ¦  «         ŒS|	                     |
d
         d         |
d
         d         z  ¦  «         Œ„t          t          j        |t          ¬¦  «        t          j        |	t          ¬¦  «        ¬¦  «        }|rt          | |¬¦  «        }nbd}t          j        t          | ¦  «        t          ¬¦  «        }t          | ¦  «        D ]\  }}|                     dg ¦  «        ||<   Œ||t           <   t          t          j        |t          ¬¦  «        |||¬¦  «        S )aƒ  Convert COCO annotation dicts for a single image into a `Detections` object.

    .. warning::
        The returned ``Detections.class_id`` contains **raw COCO** ``category_id``
        values, not the final 0-indexed internal class ids.  Callers **must** pass
        the result through :func:`map_detections_class_id` with the appropriate
        ``source_to_target_mapping`` (built by
        :func:`build_coco_class_index_mapping`) before the ``class_id`` values are
        meaningful.  Skipping the remap step yields 1-based ids in a field that the
        rest of supervision treats as 0-based.

    Args:
        image_annotations: List of COCO annotation dicts for one image.
        resolution_wh: ``(width, height)`` of the image, used for mask decoding.
        with_masks: Whether to decode segmentation fields into binary masks.
        use_iscrowd: When ``True``, store ``iscrowd`` and ``area`` in
            ``Detections.data``.

    Returns:
        Detections with ``class_id`` set to raw COCO ``category_id`` values.
        Call :func:`map_detections_class_id` on the result before use.
        When ``with_masks=False``, ``detections.data[COCO_RAW_SEGMENTATION]`` is
        populated as an object array (shape ``(N,)``) holding the raw polygon list or
        RLE dict per annotation; consumed by :func:`detections_to_coco_annotations`
        for a coordinate-preserving round-trip.
    c                ó   — g | ]
}|d          ‘ŒS )Úcategory_idr    ©r"   rs   s     r$   r%   z2coco_annotations_to_detections.<locals>.<listcomp>É   s+   € ð ð ð Ø,<Ð˜Ô'ðð ð r&   c                ó   — g | ]
}|d          ‘ŒS )Úbboxr    r~   s     r$   r%   z2coco_annotations_to_detections.<locals>.<listcomp>Ì   s   € ÐTÐTÐTÐ.>Ð! &Ô)ÐTÐTÐTr&   rO   NrT   é   r   c                ó:   — g | ]}|                      d d¦  «        ‘ŒS )Úiscrowdr   )r^   r~   s     r$   r%   z2coco_annotations_to_detections.<locals>.<listcomp>Ò   s6   € ð 
ð 
ð 
Ø3CÐ× Ò  ¨AÑ.Ô.ð
ð 
ð 
r&   Úarear€   é   )rƒ   r„   )rJ   rK   rQ   )Úclass_idÚxyxyÚmaskÚdata)r   Úemptyr[   rf   Úfloat32rG   Ú_with_seg_maskÚnanra   ÚintÚfloatrx   ÚlenÚobjectr8   r^   r   )rJ   rK   ry   rz   Ú	class_idsÚ	xyxy_listr‡   r‰   rƒ   r„   rs   rˆ   Úraw_segsÚkÚ_anns                  r$   Úcoco_annotations_to_detectionsr—   ¦   sa  € ð@ ð "ÝÔÑ!Ô!Ð!ðð Ø@Qðñ ô €Ið UÐTÐBSÐTÑTÔT€IÝ$&¤J¨yÅÄ
Ð$KÑ$KÔ$K€DØˆˆˆˆAˆaˆCˆ€L€L„L�D˜˜˜˜A˜a˜C˜”LÑ €L€L�Là;=€DØð 
ð
ð 
ØGXð
ñ 
ô 
ˆð ˆØ 1ð 	Wð 	WÐØÐ)Ð)Ð)Ø—’Ð,¨VÔ4Ñ5Ô5Ð5Ð5Øð W¥Ð/?Ñ @Ô @ð WØ—’�BœFÑ#Ô#Ð#Ð#à—’Ð,¨VÔ4°QÔ7Ð:JÈ6Ô:RÐSTÔ:UÑUÑVÔVÐVÐVÝÝ”J˜w­cÐ2Ñ2Ô2½¼ÀDÕPUÐ9VÑ9VÔ9Vð
ñ 
ô 
ˆð ð /Ý(Ø/¸}ð
ñ 
ô 
ˆˆð ˆõ -/¬HÝÐ!Ñ"Ô"­&ð-
ñ -
ô -
ˆõ !Ð!2Ñ3Ô3ð 	7ð 	7‰GˆAˆtØŸ(š( >°2Ñ6Ô6ˆH�Q‰KˆKØ&.ˆÕ"Ñ#åÝ”˜I­SÐ1Ñ1Ô1¸À4Èdðñ ô ð r&   ç        ç      ð?ç      è?Ú
detectionsrF   rŽ   Úannotation_idÚmin_image_area_percentager�   Úmax_image_area_percentageÚapproximation_percentageútuple[list[CocoDict], int]c           	     ó
  — g }| D �]ú\  }}}	}
}	}|
€t          d¦  «        ‚|d         |d         z
  |d         |d         z
  }}g }|�ú|}d|v r:t          t          j        |d         ¦  «                             ¦   «         ¦  «        }n-t          t          |¬¦  «        pt          |¬¦  «        ¦  «        }|rNt          t          t                   t          |d	¬
¦  «        ¦  «        t          |j
        dd…         ¦  «        dœ}�n t          ||||¬¦  «        }|rd„ |D ¦   «         }nþt          j        d|› d�d¬¦  «         nãt          t          j        |                     dd¦  «        ¦  «                             ¦   «         ¦  «        }|                     t          ¦  «        }|�€t!          |¦  «        rqt#          |t$          ¦  «        r|}nYt#          |t          ¦  «        r5|r3t#          |d         t          t&          f¦  «        st          |¦  «        g}nt          |¦  «        }d}t(          |v r>t+          t          j        |t(                   ¦  «                             ¦   «         ¦  «        }|�t          j        |¦  «        r|}n6|�"t+          t          j        |¦  «        ¦  «        }nt+          ||z  ¦  «        }||t          |
¦  «        dz   |d         |d         ||g|||dœ}|                     |¦  «         |dz  }�Œü||fS )aÿ	  Convert `Detections` to COCO ``annotations`` entries.

    The internal 0-indexed ``Detections.class_id`` is serialized as a 1-indexed
    COCO ``category_id`` (``category_id = class_id + 1``). This complies with the
    COCO specification and tools such as CVAT, and stays consistent with the ids
    emitted by [`classes_to_coco_categories`](#classes_to_coco_categories), so a
    detection with internal ``class_id=k`` maps to ``category_id=k + 1``.

    Args:
        detections: The detections to convert. ``class_id`` must not be ``None``.
        image_id: COCO ``image_id`` shared by every produced annotation.
        annotation_id: First annotation id to assign; incremented per detection.
        min_image_area_percentage: Lower bound on detection area / image area,
            used only when approximating masks with polygons.
        max_image_area_percentage: Upper bound on detection area / image area,
            used only when approximating masks with polygons.
        approximation_percentage: Polygon-simplification ratio in ``[0, 1)``.

    Returns:
        A ``(coco_annotations, next_annotation_id)`` tuple, where
        ``next_annotation_id`` is one greater than the last id assigned.

    Raises:
        ValueError: If any detection has ``class_id`` equal to ``None``.

    Note:
        For ``iscrowd=0`` annotations, ``segmentation`` is a
        ``list[list[float]]`` where each inner list encodes one polygon
        part as flat ``[x1, y1, x2, y2, ...]`` coordinates. A single
        object with *N* disjoint parts produces *N* inner lists.

        When ``iscrowd`` is not in ``detections.data``, masks with holes
        or multiple disjoint segments are auto-encoded as RLE
        (``iscrowd=1``); simple single-region masks use polygon format
        (``iscrowd=0``). Supply ``data={"iscrowd": np.array([0])}`` to
        force polygon output regardless of mask topology.

    Example:
        ```pycon
        >>> import numpy as np
        >>> from supervision import Detections
        >>> from supervision.dataset.formats.coco import (
        ...     detections_to_coco_annotations,
        ... )
        >>> detections = Detections(
        ...     xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32),
        ...     class_id=np.array([0], dtype=int),
        ... )
        >>> annotations, next_id = detections_to_coco_annotations(
        ...     detections=detections, image_id=1, annotation_id=1
        ... )
        >>> annotations[0]["category_id"]
        1
        >>> next_id
        2

        ```
    Nz1Detections must include class_id for COCO export.rT   r   r…   r=   rƒ   )rˆ   F)rˆ   Ú
compressed)rR   rh   )rˆ   r�   rž   rŸ   c                óP   — g | ]#}t          |                     ¦   «         ¦  «        ‘Œ$S r    )rd   Úflatten)r"   Úps     r$   r%   z2detections_to_coco_annotations.<locals>.<listcomp>Y  s(   € Ð#HÐ#HÐ#H¸!¥D¨¯ª©¬Ñ$5Ô$5Ð#HÐ#HÐ#Hr&   z5Skipping COCO polygon segmentation for annotation id=z1 because mask approximation returned no polygons.rU   )r(   rF   r}   r€   r„   rQ   rƒ   )rk   rŽ   r[   rf   Úitemr   r   r   rd   r   Úshaper   rb   rc   r^   r   r]   r`   ra   Útupler
   r�   ri   Úcount_nonzerorG   )r›   rF   rœ   r�   rž   rŸ   rC   r‡   rˆ   Ú_r†   r‰   Ú	box_widthÚ
box_heightrQ   Ú	mask_boolrƒ   rt   Úraw_segÚstored_arear„   Úcoco_annotations                         r$   Údetections_to_coco_annotationsr±   õ   sV  € ðD (*ÐØ,6ð Pñ PÑ(ˆˆd�A�x  DØÐÝÐPÑQÔQÐQØ $ Q¤¨$¨q¬'Ñ 1°4¸´7¸TÀ!¼WÑ3D�:ˆ	ØACˆØÐØˆIØ˜DÐ Ð Ý�bœj¨¨i¬Ñ9Ô9×>Ò>Ñ@Ô@ÑAÔA��åÝ"¨	Ð2Ñ2Ô2ð BÝ1°yÐAÑAÔAñô �ð
 ð å"Ý�Sœ	¥;°IÈ%Ð#PÑ#PÔ#Pñô õ ! ¤¨B¨Q¨B¤Ñ0Ô0ð	 ð  �‘õ :Ø"Ø.GØ.GØ-Eð	ñ ô �ð ð 	à#HÐ#H¸xÐ#HÑ#HÔ#H�L�Lå”Mð0Ø+ð0ð 0ð 0ð $%ð	ñ ô ð ð õ �"œ* T§X¢X¨i¸Ñ%;Ô%;Ñ<Ô<×AÒAÑCÔCÑDÔDˆGð —h’hÕ4Ñ5Ô5ˆGØÐ"¥t¨G¡}¤}Ð"Ý˜g¥tÑ,Ô,ð 1à#*�L�Lå˜w­Ñ-Ô-ð1àð1õ ' w¨q¤zµD½%°=ÑAÔAð1õ %)¨¡M¤M ?�L�Lå#'¨¡=¤=�LàˆÝ˜dÐ"Ð"Ý¥¤
¨4µÔ+@Ñ AÔ A× FÒ FÑ HÔ HÑIÔIˆKàÐ"¥r¤{°;Ñ'?Ô'?Ð"ØˆDˆDØÐÝ�Ô)¨$Ñ/Ô/Ñ0Ô0ˆDˆDå˜ ZÑ/Ñ0Ô0ˆDàØ Ý˜x™=œ=¨1Ñ,Ø˜!”W˜d 1œg y°*Ð=ØØ(Øð
ð 
ˆð 	×Ò Ñ0Ô0Ð0Ø˜Ñˆ‰Ø˜]Ð*Ð*r&   Úannotations_pathÚstrc                ó¶   — t          | ¦  «        }t          |d         ¬¦  «        }t          |d         |¬¦  «        }d„ |                     ¦   «         D ¦   «         S )aƒ	  
    Generates a mapping from sequential class indices to original COCO class ids.

    This function is essential when working with models that expect class ids to be
    zero-indexed and sequential (0 to 79), as opposed to the original COCO
    dataset where category ids are non-contiguous ranging from 1 to 90 but skipping some
    ids.

    Use Cases:
        - Evaluating models trained with COCO-style annotations where class ids
          are sequential ranging from 0 to 79.
        - Ensuring consistent class indexing across training, inference and evaluation,
          when using different tools or datasets with COCO format.
        - Reproducing results from models that assume sequential class ids (0 to 79).

    How it Works:
        - Reads the COCO annotation file in its original format (`annotations_path`).
        - Extracts and sorts all class names by their original COCO id (1 to 90).
        - Builds a mapping from COCO class ids (not sequential with skipped ids) to
          new class ids (sequential ranging from 0 to 79).
        - Returns a dictionary mapping: `{new_class_id: original_COCO_class_id}`.

    Args:
        annotations_path: Path to COCO JSON annotations file
        (e.g., `instances_val2017.json`).

    Returns:
        A mapping from new class id (sequential ranging from 0 to 79)
        to original COCO class id (1 to 90 with skipped ids).

    Examples:
        ```pycon
        >>> import json
        >>> import os
        >>> import tempfile
        >>> from supervision.dataset.formats.coco import get_coco_class_index_mapping
        >>> coco_data = {
        ...     "categories": [
        ...         {"id": 1, "name": "person"},
        ...         {"id": 3, "name": "car"},
        ...     ],
        ...     "images": [],
        ...     "annotations": [],
        ... }
        >>> annotations_path = None
        >>> try:
        ...     with tempfile.NamedTemporaryFile(
        ...         mode="w", suffix=".json", delete=False
        ...     ) as f:
        ...         annotations_path = f.name
        ...         json.dump(coco_data, f)
        ...     mapping = get_coco_class_index_mapping(annotations_path)
        ...     print(mapping)
        ... finally:
        ...     if annotations_path is not None:
        ...         os.remove(annotations_path)
        {0: 1, 1: 3}
        >>> os.path.exists(annotations_path)
        False

        ```
    Ú
categoriesr,   ©r   r.   c                ó   — i | ]\  }}||“Œ	S r    r    )r"   r•   Úvs      r$   r2   z0get_coco_class_index_mapping.<locals>.<dictcomp>Ð  s   € Ð3Ð3Ð3‘T�Q˜ˆAˆqÐ3Ð3Ð3r&   )r   r-   r9   Úitems)r²   Ú	coco_datar:   Úclass_mappings       r$   Úget_coco_class_index_mappingr¼   Œ  sh   € õ~ Ð/Ñ0Ô0€IÝ(¸À<Ô9PÐQÑQÔQ€GÝ2Ø! ,Ô/Àðñ ô €Mð 4Ð3˜]×0Ò0Ñ2Ô2Ð3Ñ3Ô3Ð3r&   FÚimages_directory_pathÚforce_masksÚshow_progressú2tuple[list[str], list[str], dict[str, Detections]]c           
     óŽ  — t          |¬¦  «        }t          |d         ¬¦  «        }t          |d         |¬¦  «        }|d         }t          |d         ¬¦  «        }	g }
i }t	          | ¦  «                             ¦   «         }t          |t          |¦  «        d| ¬	¦  «        D �]ž}|d
         |d         |d         }}}|	                     |d         g ¦  «        }t          t	          | ¦  «        t	          |¦  «        z  ¦  «        }	 t	          |¦  «                             ¦   «         }n/# t          t          f$ r}t          d|›d|› �¦  «        |‚d}~ww xY w||k    rt          d|›d|› d�¦  «        ‚||j        vrt          d|›d|› d|› d�¦  «        ‚|                     ¦   «         rt          d|›d|› d�¦  «        ‚t          |¦  «        }||v rt          d|›d�¦  «        ‚|pt          d„ |D ¦   «         ¦  «        }t          |||f||¬¦  «        }t!          ||¬¦  «        }|
                     |¦  «         |||<   �Œ ||
|fS )a  
    Load COCO annotations and convert them to `Detections`.

    If `force_masks` is `False`, masks are still loaded for images whose annotations
    include a `segmentation` field. This keeps mask handling consistent with other
    dataset loaders that infer masks from annotation content.

    Args:
        images_directory_path: Path to the image directory.
        annotations_path: Path to COCO JSON annotations.
        force_masks: If `True`, always attempt to load masks.
        use_iscrowd: If `True`, include `iscrowd` and `area` in detection data.
        show_progress: If `True`, display a progress bar during loading.

    Returns:
        A tuple of `(classes, image_paths, annotations)` where image paths are
        canonicalized resolved paths inside ``images_directory_path``.

    Raises:
        ValueError: If any annotation's ``file_name`` resolves to the images
            directory itself, to a path outside the images directory (e.g. via
            ``../`` traversal or an absolute path), or to a subdirectory instead
            of a regular image file.
        ValueError: If two image entries resolve to the same canonical path.

    Note:
        Each annotation's ``file_name`` is validated against
        ``images_directory_path`` before loading. Annotations that reference
        paths outside the directory are rejected to prevent path-traversal
        attacks when loading user-supplied annotation files. Symlinked images
        pointing outside the resolved images directory are also rejected.
    ©Ú	file_pathrµ   r,   r¶   Úimagesr   )rC   zLoading COCO annotations)ÚtotalÚdescÚdisableÚ	file_namerp   ro   r(   z COCO annotation refers to image z", which produces an invalid path: Nz1, which resolves to the images directory itself (z$). Expected a path to an image file.z, which resolves to u"    â€” outside the images directory rY   z, which resolves to directory z#. Expected a path to an image file.z:COCO annotation file contains duplicate entries for image z&. Each image must appear at most once.c              3  ó4   K  — | ]}t          |¦  «        V — Œd S ©N)rŒ   )r"   rH   s     r$   ú	<genexpr>z(load_coco_annotations.<locals>.<genexpr>8  s;   è è € ð (
ð (
Ø+5�N˜:Ñ&Ô&ð(
ð (
ð (
ð (
ð (
ð (
r&   )rJ   rK   ry   rz   )Úsource_to_target_mappingr›   )r   r-   r9   rI   r   Úresolver	   r�   r^   r³   ÚOSErrorrk   ÚparentsÚis_dirÚanyr—   r   rG   )r½   r²   r¾   rz   r¿   rº   r:   Úclass_index_mappingÚcoco_imagesÚcoco_annotations_groupsrÄ   r   Úimages_directory_resolvedÚ
coco_imageÚ
image_nameÚimage_widthÚimage_heightrJ   Ú
image_pathÚresolved_image_pathÚexcry   rH   s                          r$   Úload_coco_annotationsrÝ   Ó  s{  € õN Ð)9Ð:Ñ:Ô:€IÝ(¸À<Ô9PÐQÑQÔQ€Gå8Ø! ,Ô/Àðñ ô Ðð ˜HÔ%€KÝ@Ø" =Ô1ðñ ô Ðð €FØ€KÝ $Ð%:Ñ ;Ô ;× CÒ CÑ EÔ EÐåØÝ�+ÑÔØ'Ø!Ð!ð	ñ ô ð >-ñ >-ˆ
ð �{Ô#Ø�wÔØ�xÔ ð ".�Kˆ
ð
 4×7Ò7¸
À4Ô8HÈ"ÑMÔMÐÝ�Ð3Ñ4Ô4µt¸JÑ7GÔ7GÑGÑHÔHˆ
ð	Ý"& zÑ"2Ô"2×":Ò":Ñ"<Ô"<ÐÐøÝ�Ð$ð 	ð 	ð 	Ýð3°:ð 3ð 3Ø-0ð3ð 3ñô ð ðøøøøð	øøøð
 Ð";Ò;Ð;Ýð°:ð ð à-ðð ð ñô ð ð %Ð,?Ô,GÐGÐGÝð:°:ð :ð :Ø2ð:ð :à6ð:ð :ð :ñô ð ð
 ×%Ò%Ñ'Ô'ð 	Ýð)°:ð )ð )Ø)<ð)ð )ð )ñô ð õ
 Ð,Ñ-Ô-ˆ
Ø˜Ð$Ð$ÝðHØðHð Hð Hñô ð ð
 !ð 
¥Cð (
ð (
Ø9Jð(
ñ (
ô (
ñ %
ô %
ˆ
õ 4Ø/Ø&¨Ð5Ø!Ø#ð	
ñ 
ô 
ˆ
õ -Ø%8Ø!ð
ñ 
ô 
ˆ
ð
 	�Š�jÑ!Ô!Ð!Ø",ˆ�JÑÑà�F˜KÐ'Ð's   Ä!D(Ä(EÄ9EÅErH   údict[str, Any]c                óF   — t          |                      d¦  «        ¦  «        S )NrQ   )r]   r^   )rH   s    r$   rŒ   rŒ   M  s   € Ý�
—’˜~Ñ.Ô.Ñ/Ô/Ð/r&   Údatasetr   rÚ   c                ó~   — | j         r!| j         |         j        dd…         \  }}||fS t          |¦  «        \  }}||fS )u2  Return ``(height, width)`` for ``image_path`` without decoding pixels.

    Uses the in-memory array when the dataset holds one; otherwise reads the size from
    the file header, following its EXIF orientation the way loading the image does â€” the
    same optimization the YOLO loader uses (#1636).
    NrT   )Ú_images_in_memoryr§   r   )rà   rÚ   rÙ   rØ   s       r$   Ú_image_resolution_hwrã   Q  sX   € ð Ô ð )Ø$+Ô$=¸jÔ$IÔ$OÐPRÐQRÐPRÔ$SÑ!ˆ�kØ˜[Ð(Ð(Ý 9¸*Ñ EÔ EÑ€K�Ø˜Ð$Ð$r&   r=   Úannotation_pathÚstarting_image_idÚstarting_annotation_idc           	     óú  — |dk     s|dk     rt          d|›d|›�¦  «        ‚t          | j        d„ d¬¦  «         t          |¦  «        j                             dd¬¦  «         dd	d
dœg}g }	g }
t          | j        ¬¦  «        }||}}t          | j        d| ¬¦  «        D ]À}| j	        |         }t          | |¦  «        \  }}t          |¦  «        j        › t          |¦  «        j        › �}|d|||t          j        ¦   «                              d¦  «        dœ}|
                     |¦  «         t#          ||||||¬¦  «        \  }}|	                     |¦  «         |dz  }ŒÁi |||
|	dœ}t'          ||¬¦  «         ||fS )uy
  Save a DetectionDataset to a COCO-format ``annotations.json`` file.

    Args:
        dataset: The DetectionDataset to write.
        annotation_path: Output path for the COCO ``annotations.json``.
        min_image_area_percentage: Lower bound on detection area / image area;
            used only for segmentation datasets.
        max_image_area_percentage: Upper bound on detection area / image area;
            used only for segmentation datasets.
        approximation_percentage: Polygon-simplification ratio in ``[0, 1)``;
            used only for segmentation datasets.
        starting_image_id: First image id to assign in the exported file.
            Defaults to ``1``. Override when exporting multiple splits into
            a coordinated COCO collection so ids remain unique across the set.
        starting_annotation_id: First annotation id to assign in the exported
            file. Defaults to ``1``. Override for the same multi-split reason
            as ``starting_image_id``.
        show_progress: If ``True``, display a progress bar during saving.

    Returns:
        A ``(next_image_id, next_annotation_id)`` tuple. The returned values
        are one greater than the highest ids written, so they can be fed
        directly back into ``starting_image_id`` and ``starting_annotation_id``
        when exporting another split into a coordinated COCO collection
        (see ``DetectionDataset.as_coco`` for the chaining pattern). When the
        dataset is empty the starting ids are returned unchanged.

        .. note::
            This function ensures globally unique integer ``id`` values across
            splits. It rejects duplicate image basenames before writing because
            ``file_name`` is set to the bare image basename, so two input paths
            that differ only by directory would otherwise collapse to the same
            COCO image record.

    Raises:
        ValueError: If two image paths share the same basename and would map to
            the same COCO ``file_name``.

    Example:
        ```python
        import supervision as sv
        from supervision.dataset.formats.coco import save_coco_annotations

        ds = sv.DetectionDataset.from_yolo(
            images_directory_path="train/images",
            annotations_directory_path="train/labels",
            data_yaml_path="data.yaml",
        )
        next_img_id, next_ann_id = save_coco_annotations(
            dataset=ds, annotation_path="out/train/annotations.json"
        )
        # next_img_id and next_ann_id are the first unused ids â€” pass them
        # to the next split to keep ids globally unique across files.
        ```
    r=   ztstarting_image_id and starting_annotation_id must be >= 1 (COCO spec requires 1-indexed ids); got starting_image_id=z, starting_annotation_id=c                ó*   — t          | ¦  «        j        S rÊ   )r   r   )rÚ   s    r$   r)   z'save_coco_annotations.<locals>.<lambda>¨  s   € �t JÑ/Ô/Ô4€ r&   z
COCO image)Úimage_pathsr*   Úoutput_kindT)rÏ   Úexist_okz,https://creativecommons.org/licenses/by/4.0/z	CC BY 4.0)r(   Úurlr   rA   zSaving COCO annotations)rÆ   rÇ   z%m/%d/%Y,%H:%M:%S)r(   ÚlicenserÈ   ro   rp   Údate_captured)r›   rF   rœ   r�   rž   rŸ   )ÚinfoÚlicensesrµ   rÄ   r   rÂ   )rk   r   ré   r   ÚparentÚmkdirrB   r:   r	   r   rã   ÚstemÚsuffixr   ÚnowÚstrftimerG   r±   Úextendr   )rà   rä   r�   rž   rŸ   rå   ræ   r¿   rð   rC   rÓ   r   rF   rœ   rÚ   rH   rÙ   rØ   r×   rÖ   r°   Úannotation_dicts                         r$   Úsave_coco_annotationsrù   _  s.  € ðB ˜1ÒÐÐ 6¸Ò :Ð :ÝðCà$ðCð Cà)?ðCð Cñ
ô 
ð 	
õ
 !ØÔ'Ø4Ð4Ø ðñ ô ð õ
 	ˆÑÔÔ ×&Ò&¨t¸dÐ&ÑCÔCÐCð ØAØð	
ð 	
ð€Hð ÐØ€KÝ0¸¼ÐIÑIÔI€Oà/Ð1Gˆm€HÝØÔØ&Ø!Ð!ðñ ô ð ð ˆ
ð
 Ô(¨Ô4ˆ
õ %9¸À*Ñ$MÔ$MÑ!ˆ�kÝ˜ZÑ(Ô(Ô-ÐH­t°JÑ/?Ô/?Ô/FÐHÐHˆ
àØØ#Ø"Ø Ý%œ\™^œ^×4Ò4Ð5HÑIÔIð
ð 
ˆ
ð 	×Ò˜:Ñ&Ô&Ð&Ý)GØ!ØØ'Ø&?Ø&?Ø%=ð*
ñ *
ô *
Ñ&ˆ˜ð 	×Ò Ñ0Ô0Ð0Ø�A‰ˆˆð ØØ%ØØ'ðð €Oõ �?¨oÐ>Ñ>Ô>Ð>Ø�]Ð"Ð"r&   )r   r   r   r   )r   r   r.   r   r   r/   )r:   r   r   r   )rC   r   r   rD   )rJ   r   rK   rL   r   rM   )T)
rJ   r   rK   rL   ry   r]   rz   r]   r   r   )r˜   r™   rš   )r›   r   rF   rŽ   rœ   rŽ   r�   r�   rž   r�   rŸ   r�   r   r    )r²   r³   r   r/   )FTF)r½   r³   r²   r³   r¾   r]   rz   r]   r¿   r]   r   rÀ   )rH   rÞ   r   r]   )rà   r   rÚ   r³   r   rL   )r˜   r™   r˜   r=   r=   F)rà   r   rä   r³   r�   r�   rž   r�   rŸ   r�   rå   rŽ   ræ   rŽ   r¿   r]   r   rL   )5Ú
__future__r   rb   r   Úpathlibr   Útypingr   r   r   Únumpyr[   Únumpy.typingÚnptÚ	tqdm.autor	   Úsupervision.configr
   r   Úsupervision.dataset.utilsr   r   r   r   Úsupervision.detection.corer   Ú&supervision.detection.utils.convertersr   r   r   Ú!supervision.detection.utils.masksr   r   Úsupervision.utils.filer   r   Úsupervision.dataset.corer   ra   r³   ÚCocoDictr-   r9   rB   rI   rx   r—   r±   r¼   rÝ   rŒ   rã   rù   r    r&   r$   ú<module>r	     sç  ðØ "Ð "Ð "Ð "Ð "Ð "à €€€Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø +Ð +Ð +Ð +Ð +Ð +Ð +Ð +Ð +Ð +à Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à EÐ EÐ EÐ EÐ EÐ EÐ EÐ Eðð ð ð ð ð ð ð ð ð ð ð ð 2Ð 1Ð 1Ð 1Ð 1Ð 1ðð ð ð ð ð ð ð ð ð ð
 YÐ XÐ XÐ XÐ XÐ XÐ XÐ XØ AÐ AÐ AÐ AÐ AÐ AÐ AÐ Aàð :Ø9Ð9Ð9Ð9Ð9Ð9à��S�Œ>€ðð ð ð ð	ð 	ð 	ð 	ðð ð ð ðD	ð 	ð 	ð 	ð@)ð @)ð @)ð @)ðN ð	Lð Lð Lð Lð Lðf (+Ø'*Ø&*ðT+ð T+ð T+ð T+ð T+ðnD4ð D4ð D4ð D4ðT ØØðw(ð w(ð w(ð w(ð w(ðt0ð 0ð 0ð 0ð%ð %ð %ð %ð" (+Ø'*Ø&)ØØ"#ØðC#ð C#ð C#ð C#ð C#ð C#ð C#r&   