§
    >²¸j;  ã                  óþ   — d dl mZ d dlZd dlmZmZ d dlmZm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mZmZ d dlmZmZmZ erd d	lmZ eeef         Zd
ZdZg d¢Z d1d„Z!d2d„Z"d3d„Z#	 d4d5d#„Z$d6d(„Z%d7d,„Z&d8d0„Z'dS )9é    )ÚannotationsN)ÚPathÚPureWindowsPath)ÚTYPE_CHECKINGÚAny)Úcheck_no_basename_collisions)Ú
Detections)Úmask_to_polygonsÚpolygon_to_maskÚpolygon_to_xyxy)Úlist_files_with_extensionsÚread_json_fileÚsave_json_file)ÚDetectionDatasetz5.5.0)Ú	rectangleÚpolygon)Údetections_to_labelme_shapesÚlabelme_shapes_to_detectionsÚload_labelme_annotationsÚsave_labelme_annotationsÚpointsúnpt.NDArray[np.float32]Úreturnc           	     ór  — | d d …df         }| d d …df         }t          j        t          |                     ¦   «         ¦  «        t          |                     ¦   «         ¦  «        t          |                     ¦   «         ¦  «        t          |                     ¦   «         ¦  «        gt           j        ¬¦  «        S )Nr   é   ©Údtype)ÚnpÚarrayÚfloatÚminÚmaxÚfloat32)r   Úx_coordinatesÚy_coordinatess      ús/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/supervision/dataset/formats/labelme.pyÚ_rectangle_to_xyxyr'   '   s¥   € Ø˜1˜1˜1˜a˜4”L€MØ˜1˜1˜1˜a˜4”L€MÝŒ8å�-×#Ò#Ñ%Ô%Ñ&Ô&Ý�-×#Ò#Ñ%Ô%Ñ&Ô&Ý�-×#Ò#Ñ%Ô%Ñ&Ô&Ý�-×#Ò#Ñ%Ô%Ñ&Ô&ð		
õ Œjðñ ô ð ó    Úxyxyc                ó|   — d„ | D ¦   «         \  }}}}t          j        ||g||g||g||ggt           j        ¬¦  «        S )Nc              3  ó4   K  — | ]}t          |¦  «        V — Œd S ©N©r    ©Ú.0Úvalues     r&   ú	<genexpr>z#_xyxy_to_polygon.<locals>.<genexpr>6   s(   è è € Ð!AÐ!A°5¥%¨¡,¤,Ð!AÐ!AÐ!AÐ!AÐ!AÐ!Ar(   r   )r   r   r#   )r)   Úx_minÚy_minÚx_maxÚy_maxs        r&   Ú_xyxy_to_polygonr6   5   sX   € Ø!AÐ!A¸DÐ!AÑ!AÔ!AÑ€Eˆ5�%˜ÝŒ8Ø
�ˆ˜% ˜¨%°¨¸%À¸ÐHÝŒjðñ ô ð r(   Úshapesúlist[LabelMeDict]Úclass_to_indexúdict[str, int]Úresolution_whútuple[int, int]Ú
with_masksÚboolr	   c           
     óÒ  ‡— g }g }g }t          ¦   «         }| D �]ï}|                     d¦  «        }	|	t          vr#|                     t	          |	¦  «        ¦  «         ŒD|                     d¦  «        }
|                     d¦  «        }|
�|€|
€dnd}t          d|	›d|›d�¦  «        ‚t          j        |t          j        ¬¦  «        }|j	        d	k    s|j
        d
         d	k    rt          d|	›d|
›d|j
        › d�¦  «        ‚|	dk    rUt          |¦  «        d	k     r#t          d|
›dt          |¦  «        › d�¦  «        ‚t          |¦  «        }t          |¦  «        }net          |¦  «        dk     r#t          d|
›dt          |¦  «        › d�¦  «        ‚t          |¬¦  «                             t          j        ¦  «        }|}|                     |¦  «         |                     ||
         ¦  «         |r|                     |¦  «         �Œñ|rBt#          j        dt'          |¦  «        › dt)          t          ¦  «        › d�t*          d	¬¦  «         |st-          j        ¦   «         S t          j        |t          j        ¬¦  «        }t          j        |t0          ¬¦  «        }|st-          ||¬¦  «        S t          j        ˆfd„|D ¦   «         t2          ¬¦  «        }t-          |||¬¦  «        S )a/  Convert a single image's LabelMe shapes into ``Detections``.

    Only ``rectangle`` and ``polygon`` shapes are imported; other shape types
    (``circle``, ``line``, ``point``, ``linestrip``) are skipped with a warning.
    When ``with_masks`` is ``True``, both ``rectangle`` and ``polygon`` shapes
    produce masks: rectangles via a four-corner polygon fill.

    Args:
        shapes: List of LabelMe shape dicts for one image.
        class_to_index: Mapping from class name to integer class ID.
        resolution_wh: Image ``(width, height)`` used to rasterise masks.
        with_masks: If ``True``, produce a binary mask for every detection.

    Returns:
        A :class:`Detections` instance with ``xyxy``, ``class_id``, and
        optionally ``mask`` populated.

    Raises:
        ValueError: If a shape is missing its ``label`` or ``points`` field,
            if a ``polygon`` has fewer than 3 points, or a ``rectangle`` has
            fewer than 2 points.

    Warns:
        UserWarning: When unsupported shape types are encountered and skipped.
    Ú
shape_typeÚlabelr   NzLabelMe shape of type z is missing the required z field.r   é   r   z (label=z<) has malformed points: expected an (N, 2) array, got shape ú.r   zLabelMe rectangle shape (label=z) has z point(s); expected at least 2.é   zLabelMe polygon shape (label=z point(s); expected at least 3.)r   z*Skipped unsupported LabelMe shape type(s) z; only z are imported.)Ú
stacklevel)r)   Úclass_idc                ó�   •— g | ]B}t          t          j        |¦  «                             t          j        ¦  «        ‰¬ ¦  «        ‘ŒCS ))r   r;   )r   r   ÚroundÚastypeÚint32)r/   r   r;   s     €r&   ú
<listcomp>z0labelme_shapes_to_detections.<locals>.<listcomp>›   sZ   ø€ ð 	
ð 	
ð 	
ð
 õ	 Ýœ Ñ)Ô)×0Ò0µ´Ñ:Ô:Ø+ðñ ô ð	
ð 	
ð 	
r(   )r)   rF   Úmask)ÚsetÚgetÚSUPPORTED_SHAPE_TYPESÚaddÚstrÚ
ValueErrorr   r   r#   ÚndimÚshapeÚlenr'   r6   r   rI   ÚappendÚwarningsÚwarnÚsortedÚlistÚUserWarningr	   ÚemptyÚintr>   )r7   r9   r;   r=   Ú	xyxy_listÚ	class_idsÚpolygonsÚskipped_typesrT   r@   rA   Ú
points_rawÚmissingr   r)   r   rF   rL   s     `               r&   r   r   =   sŸ  ø€ ð> 02€IØ€IØ.0€HÝ!™eœe€Màð '%ñ '%ˆØ—Y’Y˜|Ñ,Ô,ˆ
ØÕ2Ð2Ð2Ø×Ò�c *™oœoÑ.Ô.Ð.ØØ—	’	˜'Ñ"Ô"ˆØ—Y’Y˜xÑ(Ô(ˆ
Øˆ=˜JÐ.Ø!& �g�g°HˆGÝð/¨ð /ð /Ø#ð/ð /ð /ñô ð õ ”˜*­B¬JÐ7Ñ7Ô7ˆØŒ;˜!ÒÐ˜vœ|¨Aœ°!Ò3Ð3Ýð#¨ð #ð #¸uð #ð #à”<ð#ð #ð #ñô ð ð
 ˜Ò$Ð$Ý�6‰{Œ{˜QŠˆÝ ðD°eð Dð DÝ˜6‘{”{ðDð Dð Dñô ð õ & fÑ-Ô-ˆDÝ& tÑ,Ô,ˆGˆGå�6‰{Œ{˜QŠˆÝ ðD°Eð Dð DÝ˜6‘{”{ðDð Dð Dñô ð õ #¨6Ð2Ñ2Ô2×9Ò9½"¼*ÑEÔEˆDØˆGØ×Ò˜ÑÔÐØ×Ò˜¨Ô.Ñ/Ô/Ð/Øð 	%Ø�OŠO˜GÑ$Ô$Ð$ùàð 
ÝŒð@½ÀÑ9NÔ9Nð @ð @ÝÕ.Ñ/Ô/ð@ð @ð @åØð		
ñ 	
ô 	
ð 	
ð ð "ÝÔÑ!Ô!Ð!åŒ8�I¥R¤ZÐ0Ñ0Ô0€DÝŒx˜	­Ð-Ñ-Ô-€HØð 8Ý˜t¨hÐ7Ñ7Ô7Ð7åŒ8ð	
ð 	
ð 	
ð 	
ð
 $ð	
ñ 	
ô 	
õ ð	ñ 	ô 	€Dõ ˜4¨(¸Ð>Ñ>Ô>Ð>r(   FÚimages_directory_pathrQ   Úannotations_directory_pathÚforce_masksú2tuple[list[str], list[str], dict[str, Detections]]c                óÌ  — t          d„ t          |dg¬¦  «        D ¦   «         ¦  «        }d„ |D ¦   «         }t          d„ |D ¦   «         dhz
  ¦  «        }d„ t          |¦  «        D ¦   «         }g }i }|D �]m}	|	                     dg ¦  «        }
|	                     d	¦  «        }|st	          d
¦  «        ‚t          |¦  «        j        }|r|dv rt	          d|›d�¦  «        ‚t          t          | ¦  «        |z  ¦  «        }||v rt	          d|›d�¦  «        ‚|pt          d„ |
D ¦   «         ¦  «        }|r=|	                     d¦  «        r|	                     d¦  «        st	          d|›d�¦  «        ‚t          |	                     dd¦  «        ¦  «        t          |	                     dd¦  «        ¦  «        f}t          |
|||¬¦  «        ||<   |                     |¦  «         �Œo|||fS )a¸  Load LabelMe annotations and convert them to ``Detections``.

    LabelMe stores one JSON file per image, each containing a list of ``shapes``.
    ``rectangle`` shapes become bounding boxes; ``polygon`` shapes become masks
    (and their bounding boxes); other shape types are skipped with a warning.
    When any polygon is present in a file or when ``force_masks`` is ``True``,
    both ``rectangle`` and ``polygon`` shapes produce masks: rectangles via a
    four-corner polygon fill. Class names are inferred from the labels present
    across all files and assigned sorted, zero-based ids.

    Each image is located by the basename of the JSON's ``imagePath`` joined to
    ``images_directory_path``; the directory portion of ``imagePath`` (which
    LabelMe stores relative to the JSON file) is ignored, so annotation-supplied
    path traversal cannot escape ``images_directory_path``.

    Args:
        images_directory_path: Path to the directory containing the images.
        annotations_directory_path: Path to the directory containing the LabelMe
            ``.json`` files.
        force_masks: If ``True``, load masks for every image regardless of
            whether it contains polygon shapes.

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

    Raises:
        ValueError: If an annotation's ``imagePath`` is missing, empty, or
            resolves to ``..`` or ``.``; if two annotation files reference the
            same image basename; or if a polygon mask is requested for a file
            missing ``imageWidth`` / ``imageHeight``.

    Examples:
        ```python
        from supervision.dataset.formats.labelme import load_labelme_annotations

        classes, image_paths, annotations = load_labelme_annotations(
            images_directory_path="<IMAGES_DIRECTORY_PATH>",
            annotations_directory_path="<ANNOTATIONS_DIRECTORY_PATH>",
        )

        classes
        # ['dog', 'person']
        ```
    c              3  ó4   K  — | ]}t          |¦  «        V — Œd S r,   )rQ   )r/   Úpaths     r&   r1   z+load_labelme_annotations.<locals>.<genexpr>Ø   s<   è è € ð ð àõ 	ˆD‰	Œ	ðð ð ð ð ð r(   Újson)Ú	directoryÚ
extensionsc                ó.   — g | ]}t          |¬ ¦  «        ‘ŒS ))Ú	file_path)r   )r/   Úannotation_paths     r&   rK   z,load_labelme_annotations.<locals>.<listcomp>á   s3   € ð "ð "ð "àõ 	 Ð1Ñ1Ô1ð"ð "ð "r(   c                ó¢   — h | ]L}|                      d g ¦  «        D ]3}|                      d¦  «        t          v ¯|                      d¦  «        ’Œ4ŒMS )r7   r@   rA   )rN   rO   )r/   ÚentryrT   s      r&   ú	<setcomp>z+load_labelme_annotations.<locals>.<setcomp>ç   sl   € ð 	
ð 	
ð 	
àØŸš 8¨RÑ0Ô0ð	
ð 	
ð Ø�yŠy˜Ñ&Ô&Õ*?Ð?Ð?ð �IŠI�gÑÔð @Ð?Ð?Ð?r(   Nc                ó   — i | ]\  }}||“Œ	S © ru   )r/   ÚindexÚ
class_names      r&   ú
<dictcomp>z,load_labelme_annotations.<locals>.<dictcomp>ï   s   € ÐTÐTÐTÑ,=¨E°:�j %ÐTÐTÐTr(   r7   Ú	imagePathzSA LabelMe annotation file is missing the required 'imagePath' field or it is empty.)z..rC   z.LabelMe annotation has an invalid 'imagePath' rC   zDuplicate image basename ze resolved from multiple annotation files. All annotation files must reference unique image basenames.c              3  óH   K  — | ]}|                      d ¦  «        dk    V — ŒdS )r@   r   N)rN   )r/   rT   s     r&   r1   z+load_labelme_annotations.<locals>.<genexpr>  sD   è è € ð (
ð (
Ø5:ˆE�IŠI�lÑ#Ô# yÒ0ð(
ð (
ð (
ð (
ð (
ð (
r(   Ú
imageWidthÚimageHeightzLabelMe annotation for zV requires 'imageWidth' and 'imageHeight' to build masks, but they are missing or zero.r   )r7   r9   r;   r=   )rY   r   Ú	enumeraterN   rR   r   ÚnamerQ   r   Úanyr]   r   rV   )rd   re   rf   Úannotation_pathsÚentriesÚclassesr9   Úimage_pathsr   rr   r7   Úraw_image_pathÚ
image_nameÚ
image_pathr=   r;   s                   r&   r   r   §   sÀ  € õb ð ð å.Ø0¸f¸Xð
ñ 
ô 
ðñ ô ñ ô Ðð"ð "à/ð"ñ "ô "€Gõ
 ð	
ð 	
à ð	
ñ 	
ô 	
ð ˆ&ñ	ñô €Gð UÐTÅÈ7ÑASÔASÐTÑTÔT€Nà€KØ)+€KØð -'ñ -'ˆØ—’˜8 RÑ(Ô(ˆØŸš ;Ñ/Ô/ˆØð 	Ýð4ñô ð õ % ^Ñ4Ô4Ô9ˆ
Øð 	˜Z¨;Ð6Ð6ÝØTÀÐTÐTÐTñô ð õ �Ð3Ñ4Ô4°zÑAÑBÔBˆ
Ø˜Ð$Ð$Ýð#¨Jð #ð #ð #ñô ð ð
 !ð 
¥Cð (
ð (
Ø>Dð(
ñ (
ô (
ñ %
ô %
ˆ
ð ð 	˜uŸyšy¨Ñ6Ô6ð 	¸5¿9º9À]Ñ;SÔ;Sð 	Ýð#¨*ð #ð #ð #ñô ð õ �—	’	˜,¨Ñ*Ô*Ñ+Ô+Ý�—	’	˜-¨Ñ+Ô+Ñ,Ô,ð
ˆõ #?ØØ)Ø'Ø!ð	#
ñ #
ô #
ˆ�JÑð 	×Ò˜:Ñ&Ô&Ð&Ñ&à�K Ð,Ð,r(   rA   úlist[list[float]]r@   ÚLabelMeDictc                ó   — | |d d|i dœS )NÚ )rA   r   Úgroup_idÚdescriptionr@   Úflagsru   )rA   r   r@   s      r&   Ú_build_shaperŽ   %  s#   € àØØØØ Øðð ð r(   Ú
detectionsr‚   ú	list[str]c                ó¶  — | j         }|€t          d¦  «        ‚| j        }g }t          t	          | ¦  «        ¦  «        D �]}t          ||         ¦  «        }|dk     s|t	          |¦  «        k    r&t          d|› d|› dt	          |¦  «        › d�¦  «        ‚||         }|�6t          j        ||         t          j        ¬¦  «        }t          |¦  «        }	ng }	|	r6|	D ]2}
d	„ |
D ¦   «         }| 
                    t          ||d
¦  «        ¦  «         Œ3ŒÑd„ | j        |         D ¦   «         \  }}}}||g||gg}| 
                    t          ||d¦  «        ¦  «         �Œ|S )uÏ  Convert ``Detections`` into a list of LabelMe shape dicts.

    Masked detections are exported as ``polygon`` shapes (one per connected
    component); box-only detections â€” and masked detections whose mask yields no
    polygon contour (e.g. an empty or sub-pixel mask) â€” are exported as
    ``rectangle`` shapes, so no detection is silently dropped.

    Args:
        detections: The detections to export.
        classes: List of class names indexed by ``class_id``.

    Returns:
        A list of LabelMe shape dicts ready to embed in a ``.json`` annotation.

    Raises:
        ValueError: If ``detections.class_id`` is ``None`` or if any
            ``class_id`` value is out of range for ``classes``.
    NzWclass_id is required for LabelMe export, but the provided Detections has class_id=None.r   z	class_id z at detection index z, is out of range for classes list of length rC   r   c                óP   — g | ]#\  }}t          |¦  «        t          |¦  «        g‘Œ$S ru   r-   )r/   ÚxÚys      r&   rK   z0detections_to_labelme_shapes.<locals>.<listcomp>\  s-   € ÐCÐCÐC±4°1°a�5 ™8œ8¥U¨1¡X¤XÐ.ÐCÐCÐCr(   r   c              3  ó4   K  — | ]}t          |¦  «        V — Œd S r,   r-   r.   s     r&   r1   z/detections_to_labelme_shapes.<locals>.<genexpr>_  s9   è è € ð *ð *Ø!&•�e‘”ð*ð *ð *ð *ð *ð *r(   r   )rF   rR   rL   ÚrangerU   r]   r   ÚasarrayÚbool_r
   rV   rŽ   r)   )r�   r‚   r_   Úmasksr7   rv   Úclass_indexrA   Úmask_arrr`   r   r   r2   r3   r4   r5   s                   r&   r   r   0  sÌ  € ð* Ô#€IØÐÝð,ñ
ô 
ð 	
ð ŒO€EØ "€FÝ•s˜:‘”Ñ'Ô'ð Dñ DˆÝ˜) EÔ*Ñ+Ô+ˆØ˜Š?ˆ?˜k­S°©\¬\Ò9Ð9ÝðD˜Kð Dð D¸Uð Dð DÝ47¸±L´LðDð Dð Dñô ð ð ˜Ô$ˆØÐÝ”z %¨¤,µb´hÐ?Ñ?Ô?ˆHÝ'¨Ñ1Ô1ˆHˆHàˆHØð 		DØ#ð Fð F�ØCÐC¸7ÐCÑCÔC�Ø—’�l¨5°&¸)ÑDÔDÑEÔEÐEÐEðFð*ð *Ø*4¬/¸%Ô*@ð*ñ *ô *Ñ&ˆE�5˜% ð ˜e�n u¨e nÐ5ˆFØ�MŠM�, u¨f°kÑBÔBÑCÔCÐCÑCØ€Mr(   Údatasetr   ÚNonec           
     óÎ  — t          | j        d„ d¬¦  «         t          |¦  «                             dd¬¦  «         | D ]¥\  }}}|j        \  }}}t
          i t          || j        ¬¦  «        t          |¦  «        j        dt          |¦  «        t          |¦  «        dœ}t          |¦  «        t          |¦  «        j
        › d	�z  }	t          |t          |	¦  «        ¬
¦  «         Œ¦dS )a0  Export a ``DetectionDataset`` to per-image LabelMe ``.json`` files.

    Args:
        dataset: The ``DetectionDataset`` to write.
        annotations_directory_path: Directory where the LabelMe ``.json`` files
            are written (created if it does not exist).

    Raises:
        ValueError: If two image paths map to the same output .json stem,
            which would cause one annotation file to overwrite another.

    Examples:
        ```python
        import supervision as sv
        from supervision.dataset.formats.labelme import save_labelme_annotations

        dataset = sv.DetectionDataset(classes=["dog"], images=[], annotations={})
        save_labelme_annotations(
            dataset=dataset,
            annotations_directory_path="<ANNOTATIONS_DIRECTORY_PATH>",
        )
        ```
    c                ó0   — t          | ¦  «        j        › d�S )Nú.json)r   Ústem)r†   s    r&   ú<lambda>z*save_labelme_annotations.<locals>.<lambda>„  s   € ¥$ zÑ"2Ô"2Ô"7Ð>Ð>Ð>€ r(   zLabelMe annotation)rƒ   ÚkeyÚoutput_kindT)ÚparentsÚexist_ok)r�   r‚   N)Úversionr�   r7   ry   Ú	imageDatar|   r{   r    )Údataro   )r   rƒ   r   ÚmkdirrT   Ú_LABELME_EXPORT_VERSIONr   r‚   r~   r]   r¡   r   rQ   )
rœ   re   r†   Úimager�   Úimage_heightÚimage_widthÚ_Úlabelme_dictrp   s
             r&   r   r   g  s   € õ6 !ØÔ'Ø>Ð>Ø(ðñ ô ð õ
 	Ð	#Ñ$Ô$×*Ò*°4À$Ð*ÑGÔGÐGØ)0ð Jð JÑ%ˆ
�E˜:Ø',¤{Ñ$ˆ�k 1å.ØÝ2Ø%¨w¬ðñ ô õ ˜jÑ)Ô)Ô.ØÝ˜|Ñ,Ô,Ý˜kÑ*Ô*ð
%
ð 
%
ˆõ Ð+Ñ,Ô,µ$°zÑ2BÔ2BÔ2GÐ/NÐ/NÐ/NÑNð 	õ 	˜LµC¸Ñ4HÔ4HÐIÑIÔIÐIÐIð!Jð Jr(   )r   r   r   r   )r)   r   r   r   )
r7   r8   r9   r:   r;   r<   r=   r>   r   r	   )F)rd   rQ   re   rQ   rf   r>   r   rg   )rA   rQ   r   r‡   r@   rQ   r   rˆ   )r�   r	   r‚   r�   r   r8   )rœ   r   re   rQ   r   r�   )(Ú
__future__r   rW   Úpathlibr   r   Útypingr   r   Únumpyr   Únumpy.typingÚnptÚsupervision.dataset.utilsr   Úsupervision.detection.corer	   Ú&supervision.detection.utils.convertersr
   r   r   Úsupervision.utils.filer   r   r   Úsupervision.dataset.corer   ÚdictrQ   rˆ   r«   rO   Ú__all__r'   r6   r   r   rŽ   r   r   ru   r(   r&   ú<module>r¾      sî  ðØ "Ð "Ð "Ð "Ð "Ð "à €€€Ø )Ð )Ð )Ð )Ð )Ð )Ð )Ð )Ø %Ð %Ð %Ð %Ð %Ð %Ð %Ð %à Ð Ð Ð Ø Ð Ð Ð Ð Ð à BÐ BÐ BÐ BÐ BÐ BØ 1Ð 1Ð 1Ð 1Ð 1Ð 1ðð ð ð ð ð ð ð ð ð ð
ð ð ð ð ð ð ð ð ð ð ð :Ø9Ð9Ð9Ð9Ð9Ð9à�3˜�8Œn€à!Ð Ø0Ð ðð ð €ðð ð ð ðð ð ð ðg?ð g?ð g?ð g?ðZ ð{-ð {-ð {-ð {-ð {-ð|ð ð ð ð4ð 4ð 4ð 4ðn1Jð 1Jð 1Jð 1Jð 1Jð 1Jr(   