Ë
    ¼Ó^jc  ã                   óÆ  — d dl Z d dlmZ d dlmZ d dlmZ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 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"de#e"   de#e!   fd„Z$de#e"   de#e!   de e%e%f   fd„Z&de#e!   de#e"   fd„Z'de#e"   de e%e#e"   f   fd„Z(de#e"   de)e%e%f   dejT                  e
jV                     fd„Z,	 d/de#e"   de)e%e%f   de-de-def
d„Z.	 	 	 d0dede%de%de/de/d e/de)e#e"   e%f   fd!„Z0d"e!de e%e%f   fd#„Z1	 	 d1d$e!d"e!d%e-de-de)e#e!   e#e!   e e!ef   f   f
d&„Z2d'e e!ef   de-fd(„Z3	 	 	 	 	 d2d)d*d+e!de/de/d e/d,e%d-e%de)e%e%f   fd.„Z4y)3é    N)Údatetime)ÚPath)ÚTYPE_CHECKINGÚAnyÚUnionÚcast)ÚCOCO_RAW_SEGMENTATION)Úapproximate_mask_with_polygonsÚ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Úreturnc                 óJ   — t        | d„ ¬«      D �cg c]  }|d   ‘Œ	 c}S c c}w )Nc                 ó   — | d   S )NÚid© )Úcategorys    úk/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/supervision/dataset/formats/coco.pyú<lambda>z,coco_categories_to_classes.<locals>.<lambda>    s
   € ÀXÈdÁ^€ ó    )ÚkeyÚname)Úsorted)r   r   s     r   Úcoco_categories_to_classesr"      s1   € ô ˜Ñ4SÔTöàð 	�Óòð ùò s   ‘ Útarget_classesc                 óˆ   — | D �ci c]  }|d   |d   “Œ }}t        |«      D ��ci c]  \  }}||   |“Œ c}}S c c}w c c}}w )Nr    r   ©Ú	enumerate)r   r#   r   Úsource_class_to_indexÚtarget_class_indexÚtarget_class_names         r   Úbuild_coco_class_index_mappingr*   $   sl   € ð :IöØ-5ˆ�Ñ˜( 4™.Ñ(ðÐð ô
 6?¸~Ó5N÷á1ÐÐ 1ð 	Ð/Ñ0Ð2DÑDóð ùòùós   …9¥>Úclassesc                 óX   — t        | «      D ��cg c]  \  }}|dz   |ddœ‘Œ c}}S c c}}w )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.

    Examples:
        ```python
        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"},
        # ]
        ```
    é   zcommon-objects)r   r    Úsupercategoryr%   )r+   Úclass_indexÚ
class_names      r   Úclasses_to_coco_categoriesr1   0   s?   € ô@ (1°Ó'9÷ñ $ˆK˜ð	  ‘/ØØ-ó	
óð ùó s   �&Úcoco_annotationsc                 ó\   — i }| D ]$  }|d   }||vrg ||<   ||   j                  |«       Œ& |S )NÚimage_id)Úappend)r2   ÚannotationsÚ
annotationr4   s       r   Ú"group_coco_annotations_by_image_idr8   T   sO   € ð .0€KØ&ò 1ˆ
Ø˜jÑ)ˆØ˜;Ñ&Ø$&ˆK˜Ñ!Ø�HÑ×$Ñ$ ZÕ0ð	1ð
 Ðr   Úimage_annotationsÚresolution_whc                 ór  — |d   |d   }}t        j                  ||ft        ¬«      }g }| D �]n  }|j                  d«      }|s |j	                  |j                  «       «       Œ7|j                  dd«      r |j	                  t        |d   |¬«      «       Œit        |t        «      s |j	                  |j                  «       «       Œ™t        |d   t        «      r|n|g}|j                  «       }	|D ]˜  }
t        j                  t        j                  |
t         j                  ¬«      d«      }|j                  dk(  r+t        j                  d	|j                  d
«      › d�d¬«       Œv|	t        ||¬«      j!                  t        «      z  }	Œš |j	                  |	«       �Œq t        j                  |t        ¬«      S )Nr-   r   ©ÚdtypeÚsegmentationÚiscrowdÚcounts)Úrler:   )éÿÿÿÿé   zISkipping empty polygon while loading COCO segmentation for annotation id=r   ú.rC   ©Ú
stacklevel)Úpolygonr:   )ÚnpÚzerosÚboolÚgetr5   Úcopyr   Ú
isinstanceÚlistÚreshapeÚasarrayÚint32ÚsizeÚwarningsÚwarnr   Úastype)r9   r:   ÚheightÚwidthÚ
empty_maskÚmasksÚimage_annotationr>   ÚpolygonsÚobject_maskrG   Úpolygon_arrays               r   Úcoco_annotations_to_masksr^   `   s”  € ð " !Ñ$ m°AÑ&6ˆE€FÜ(*¯©°&¸%°ÌÔ(M€JØ€Eà-ó %"ÐØ'×+Ñ+¨NÓ;ˆÙð �L‰L˜Ÿ™Ó*Ô+Øà×Ñ 	¨1Ô-Ø�L‰LÜ ¨XÑ 6ÀmÔTôð ä˜,¬Ô-Ø�L‰L˜Ÿ™Ó*Ô+ØÜ#-¨l¸1©o¼tÔ#D‘<È<È.ˆà —o‘oÓ'ˆØò 	ˆGÜ35·:±:Ü—
‘
˜7¬"¯(©(Ô3°Wó4ˆMð ×!Ñ! QÒ&Ü—‘ð%Ø%5×%9Ñ%9¸$Ó%?Ð$@ÀðCà õð
 ð œ?Ø%°]ôç‰f”T‹lñ‰Kð	ð" 	�‰�[Ö!ðK%"ôN �:‰:�e¤4Ô(Ð(r   Ú
with_masksÚuse_iscrowdc                 ó  — | st        j                  «       S | D �cg c]  }|d   ‘Œ	 }}| D �cg c]  }|d   ‘Œ	 }}t        j                  |t        j                  ¬«      }|dd…dd…fxx   |dd…dd…f   z  cc<   i }|rc| D �cg c]  }|d   ‘Œ	 }	}| D �cg c]  }|d	   ‘Œ	 }
}t        t        j                  |	t        ¬«      t        j                  |
t        ¬«      ¬
«      }|rt        | |¬«      }nWd}t        j                  t        | «      t        ¬«      }t        | «      D ]  \  }}|j                  dg «      ||<   Œ ||t        <   t        t        j                  |t        ¬«      |||¬«      S c c}w c c}w c c}w c c}w )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.
    Úcategory_idÚbboxr<   NrC   é   r   r?   Úarea)r?   re   )r9   r:   r>   )Úclass_idÚxyxyÚmaskÚdata)r   ÚemptyrH   rP   Úfloat32ÚdictÚintÚfloatr^   ÚlenÚobjectr&   rK   r	   )r9   r:   r_   r`   rZ   Ú	class_idsÚ	xyxy_listrg   ri   r?   re   rh   Úraw_segsÚkÚ_anns                  r   Úcoco_annotations_to_detectionsrv   ‘   s£  € ñ@ Ü×ÑÓ!Ð!ð ARöØ,<Ð˜Ó'ð€Ið ð CTÖTÐ.>Ð! &Ó)ÐT€IÐTÜ$&§J¡J¨yÄÇ
Á
Ô$K€DØŠˆAˆaˆCˆƒL�Dš˜A˜a˜C˜‘LÑ ƒLàAC€DÙà@Qö
Ø,<Ð˜YÓ'ð
ˆð 
ð BSÖSÐ-=Ð  Ó(ÐSˆÐSÜÜ—J‘J˜w¬cÔ2¼¿¹ÀDÔPUÔ9Vô
ˆñ Ü(Ø/¸}ô
‰ð ˆô -/¯H©HÜÐ!Ó"¬&ô-
ˆô !Ð!2Ó3ò 	7‰GˆAˆtØŸ(™( >°2Ó6ˆH�QŠKð	7à&.ˆÔ"Ñ#äÜ—‘˜I¬SÔ1¸À4Èdôð ùòAùò Uùò
ùò Ts   ›E2­E7ÂE<ÂFÚ
detectionsr4   Úannotation_idÚmin_image_area_percentageÚmax_image_area_percentageÚapproximation_percentagec           
      ó  — g }| D �]p  \  }}}	}
}	}|
€t        d«      ‚|d   |d   z
  |d   |d   z
  }}g }|��t        t        j                  t        j
                     |«      }d|v r0t        t	        j                  |d   «      j                  «       «      }n#t        t        |¬«      xs t        |¬«      «      }|r=t        t        t           t        |d	¬
«      «      t        |j                  dd «      dœ}�nt        ||||¬«      }|r'|D �cg c]  }t        |j                  «       «      ‘Œ }}nÐt!        j"                  d|› d�d¬«       n´t        t	        j                  |j%                  dd«      «      j                  «       «      }|j%                  t&        «      }|�at)        |«      rVt+        |t,        «      r|}nCt+        |t        «      r(|r&t+        |d   t        t.        f«      st        |«      g}nt        |«      }t1        t	        j                  |j%                  d||z  «      «      j                  «       «      }||t        |
«      dz   |d   |d   ||g|||dœ}|j3                  |«       |dz  }�Œs ||fS c c}w )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.

    Examples:
        ```python
        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
        ```
    Nz1Detections must include class_id for COCO export.rC   r   é   r-   r?   )rh   F)rh   Ú
compressed)r@   rR   )rh   ry   rz   r{   z5Skipping COCO polygon segmentation for annotation id=z1 because mask approximation returned no polygons.rE   re   )r   r4   rb   rc   re   r>   r?   )Ú
ValueErrorr   ÚnptÚNDArrayrH   Úbool_rm   rP   Úitemr   r   rN   r   Úshaper
   ÚflattenrS   rT   rK   r	   rJ   rM   rl   Útuplern   r5   )rw   r4   rx   ry   rz   r{   r2   rg   rh   Ú_rf   ri   Ú	box_widthÚ
box_heightr>   Ú	mask_boolr?   r[   ÚpÚraw_segre   Úcoco_annotations                         r   Údetections_to_coco_annotationsrŽ   Ù   s~  € ð@ (*ÐØ,6ó GÑ(ˆˆd�A�x  DØÐÜÐPÓQÐQØ $ Q¡¨$¨q©'Ñ 1°4¸±7¸TÀ!¹WÑ3D�:ˆ	ØGIˆØÑÜœSŸ[™[¬¯©Ñ2°DÓ9ˆIØ˜DÑ ÜœbŸj™j¨¨i©Ó9×>Ñ>Ó@ÓA‘äÜ"¨	Ô2ò BÜ1°yÔAó�ñ
 ä"ÜœS™	¤;°IÈ%Ô#Póô ! §¡¨B¨Q Ó0ñ	 ’ô :Ø"Ø.GØ.GØ-Eô	�ñ à?GÖ#H¸!¤D¨¯©«Õ$5Ð#H�LÑ#Hä—M‘MðØ+˜_ð -0ð0ð $%ö	ô œ"Ÿ*™* T§X¡X¨i¸Ó%;Ó<×AÑAÓCÓDˆGð —h‘hÔ4Ó5ˆGØÐ"¤t¨G¤}Ü˜g¤tÔ,à#*‘Lä˜w¬Ô-ÙÜ& w¨q¡z´D¼%°=ÔAô %)¨£M ?‘Lä#'¨£=�LäœBŸJ™J t§x¡x°¸	ÀJÑ8NÓ'OÓP×UÑUÓWÓXˆàØ Ü˜x›=¨1Ñ,Ø˜!‘W˜d 1™g y°*Ð=ØØ(Øñ
ˆð 	×Ñ Ô0Ø˜ÑŠðOGðP ˜]Ð*Ð*ùòO $Is   Ä I=Úannotations_pathc                 óª   — t        | «      }t        |d   ¬«      }t        |d   |¬«      }|j                  «       D ��ci c]  \  }}||“Œ
 c}}S c c}}w )ay  
    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).
    Ú
categories©r   ©r   r#   )r   r"   r*   Úitems)r�   Ú	coco_datar+   Úclass_mappingrt   Úvs         r   Úget_coco_class_index_mappingr˜   e  sY   € ô> Ð/Ó0€IÜ(¸À<Ñ9PÔQ€GÜ2Ø! ,Ñ/Àô€Mð +×0Ñ0Ó2×3‘T�Q˜ˆAˆq‰DÓ3Ð3ùÓ3s   ¾AÚimages_directory_pathÚforce_masksc           
      ó0  — t        |¬«      }t        |d   ¬«      }t        |d   |¬«      }|d   }t        |d   ¬«      }g }	i }
t	        | «      j                  «       }|D �]  }|d   |d	   |d
   }}}|j                  |d   g «      }t        t	        | «      t	        |«      z  «      }	 t	        |«      j                  «       }||k(  rt        d|›d|› d�«      ‚||j                  vrt        d|›d|› d|› d�«      ‚|j                  «       rt        d|›d|› d�«      ‚|xs t        d„ |D «       «      }t        |||f||¬«      }t        ||¬«      }|	j                  |«       ||
|<   �Œ
 ||	|
fS # t        t        f$ r}t        d|›d|› �«      |‚d}~ww xY w)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.

    Returns:
        A tuple of `(classes, image_paths, annotations)`.

    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.

    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“   Úimagesr6   )r2   Ú	file_namerW   rV   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 rD   z, which resolves to directory z#. Expected a path to an image file.c              3   ó2   K  — | ]  }t        |«      –— Œ y ­w)N)Ú_with_seg_mask)Ú.0r7   s     r   ú	<genexpr>z(load_coco_annotations.<locals>.<genexpr>â  s   è ø€ ò (
Ø+5ŒN˜:×&ñ(
ùs   ‚)r9   r:   r_   r`   )Úsource_to_target_mappingrw   )r   r"   r*   r8   r   ÚresolverK   ÚstrÚOSErrorr   ÚparentsÚis_dirÚanyrv   r   r5   )r™   r�   rš   r`   r•   r+   Úclass_index_mappingÚcoco_imagesÚcoco_annotations_groupsrž   r6   Úimages_directory_resolvedÚ
coco_imageÚ
image_nameÚimage_widthÚimage_heightr9   Ú
image_pathÚresolved_image_pathÚexcr_   r7   s                         r   Úload_coco_annotationsr¶   Œ  sZ  € ôF Ð)9Ô:€IÜ(¸À<Ñ9PÔQ€Gä8Ø! ,Ñ/ÀôÐð ˜HÑ%€KÜ@Ø" =Ñ1ôÐð €FØ€KÜ $Ð%:Ó ;× CÑ CÓ EÐà!ó 3-ˆ
à�{Ñ#Ø�wÑØ�xÑ ð ".�Kˆ
ð
 4×7Ñ7¸
À4Ñ8HÈ"ÓMÐÜœÐ3Ó4´t¸JÓ7GÑGÓHˆ
ð	Ü"& zÓ"2×":Ñ":Ó"<Ðð Ð";Ò;ÜØ2°:°.ð Aà-Ð.ð /ðóð ð %Ð,?×,GÑ,GÑGÜØ2°:°.ð AØ2Ð3ð 4Ø6Ð7°qð:óð ð
 ×%Ñ%Ô'ÜØ2°:°.ð A)Ø)<Ð(=ð >)ð)óð ð !ò 
¤Cñ (
Ø9Jô(
ó %
ˆ
ô 4Ø/Ø&¨Ð5Ø!Ø#ô	
ˆ
ô -Ø%8Ø!ô
ˆ
ð
 	�‰�jÔ!Ø",ˆ�JÓðg3-ðj �F˜KÐ'Ð'øôW œÐ$ò 	ÜØ2°:°.ð A-Ø-0¨Eð3óð ðûð	ús   Â(E/Å/FÅ>FÆFr7   c                 ó6   — t        | j                  d«      «      S )Nr>   )rJ   rK   )r7   s    r   r¡   r¡   ÷  s   € Ü�
—‘˜~Ó.Ó/Ð/r   Údatasetr   Úannotation_pathÚstarting_image_idÚstarting_annotation_idc           	      óX  — |dk  s|dk  rt        d|›d|›�«      ‚t        |«      j                  j                  dd¬«       ddddœg}g }g }	t	        | j
                  ¬	«      }
||}}| D ]§  \  }}}|j                  \  }}}t        |«      j                  › t        |«      j                  › �}|d|||t        j                  «       j                  d
«      dœ}|	j                  |«       t        ||||||¬«      \  }}|j                  |«       |dz  }Œ© i ||
|	|dœ}t        ||¬«       ||fS )ul
  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``.

    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 does **not** ensure unique ``file_name`` values â€” the
            ``file_name`` field is set to the bare image basename, so splits
            that share filenames (e.g. ``000001.jpg`` in both train and valid)
            will have duplicate ``file_name`` values when their COCO files are
            merged. Use distinct output directories or rename images before
            merging if downstream tools require unique ``file_name`` keys.

    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=T)r¨   Úexist_okz,https://creativecommons.org/licenses/by/4.0/z	CC BY 4.0)r   Úurlr    )r+   z%m/%d/%Y,%H:%M:%S)r   ÚlicenserŸ   rV   rW   Údate_captured)rw   r4   rx   ry   rz   r{   )ÚinfoÚlicensesr‘   rž   r6   rœ   )r   r   ÚparentÚmkdirr1   r+   r„   ÚstemÚsuffixr   ÚnowÚstrftimer5   rŽ   Úextendr   )r¸   r¹   ry   rz   r{   rº   r»   rÂ   r2   r¬   r   r4   rx   r³   Úimager7   r²   r±   r‡   r°   r¯   r�   Úannotation_dicts                          r   Úsave_coco_annotationsrÌ   û  sˆ  € ðz ˜1ÒÐ 6¸Ò :Üð&à$Ð&Ð&@Ð)?Ð(AðCó
ð 	
ô
 	ˆÓ× Ñ ×&Ñ&¨t¸dÐ&ÔCð ØAØñ	
ð€Hð ÐØ€KÜ0¸¿¹ÔI€Oà/Ð1Gˆm€HØ)0ò Ñ%ˆ
�E˜:Ø',§{¡{Ñ$ˆ�k 1Ü˜ZÓ(×-Ñ-Ð.¬t°JÓ/?×/FÑ/FÐ.GÐHˆ
àØØ#Ø"Ø Ü%Ÿ\™\›^×4Ñ4Ð5HÓIñ
ˆ
ð 	×Ñ˜:Ô&Ü)GØ!ØØ'Ø&?Ø&?Ø%=ô*
Ñ&ˆ˜ð 	×Ñ Ô0Ø�A‰‰ð/ð4 ØØ%ØØ'ñ€Oô �?¨oÕ>Ø�]Ð"Ð"r   )T)ç        ç      ð?g      è?)FT)rÍ   rÎ   rÍ   r-   r-   )5rS   r   Úpathlibr   Útypingr   r   r   r   ÚnumpyrH   Únumpy.typingr€   Úsupervision.configr	   Úsupervision.dataset.utilsr
   r   Úsupervision.detection.corer   Ú&supervision.detection.utils.convertersr   r   r   Ú!supervision.detection.utils.masksr   r   Úsupervision.utils.filer   r   Úsupervision.dataset.corer   rl   r¦   ÚCocoDictrN   r"   rm   r*   r1   r8   r†   r�   r‚   r^   rJ   rv   rn   rŽ   r˜   r¶   r¡   rÌ   r   r   r   ú<module>rÛ      sÌ  ðÛ Ý Ý ß 2Ó 2ã Ý å 4÷õ 2÷ñ ÷
 Yß AáÝ9à��S�‰>€ð°°X±ð À4ÈÁ9ó ð	Ø˜(‘^ð	Ø59¸#±Yð	à	ˆ#ˆsˆ(�^ó	ð!¨¨S©	ð !°d¸8±nó !ðH	Ø˜8‘nð	à	ˆ#ˆt�H‰~Ð
Ñó	ð.)Ø˜H‘~ð.)Ø6;¸CÀ¸H±oð.)à‡[�[�—‘Ñó.)ðj ñ	EØ˜H‘~ðEà˜˜c˜‘?ðEð ðEð ð	Eð
 óEðX (+Ø'*Ø&*ñI+ØðI+àðI+ð ðI+ð  %ð	I+ð
  %ðI+ð $ðI+ð ˆ4�‰>˜3ÐÑóI+ðX$4°3ð $4¸4ÀÀSÀ¹>ó $4ðT Øñ	h(Øðh(àðh(ð ðh(ð ð	h(ð
 ˆ4�‰9�d˜3‘i  c¨: oÑ!6Ð6Ñ7óh(ðV0˜t C¨ H™~ð 0°$ó 0ð (+Ø'*Ø&)ØØ"#ñr#Øðr#àðr#ð  %ðr#ð  %ð	r#ð
 $ðr#ð ðr#ð  ðr#ð ˆ3�ˆ8�_ôr#r   