§
    >²¸j¹1  ã                  ó¾   — 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 d dlmZmZ erd d	lmZ eeef         Zd#d„Zd$d„Z	 d%d&d„Zd'd„Zd(d"„ZdS ))é    )Úannotations)ÚPath)ÚTYPE_CHECKINGÚAnyÚcastN)Útqdm)Úcheck_no_basename_collisions)Ú
Detections)Úread_json_fileÚsave_json_file)ÚDetectionDatasetÚimages_directory_pathÚstrÚ
image_nameÚreturnc           	     óú  — t          | ¦  «                             ¦   «         }t          | ¦  «        t          |¦  «        z  }	 |                     ¦   «         }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          |¦  «        S )ap  Resolve and validate an image path against the images directory.

    Rejects annotations whose ``image`` field escapes ``images_directory_path``
    (via ``..`` traversal, an absolute path, or a symlink pointing outside),
    mirroring the protection used by the COCO loader. Returns the canonical
    resolved path so aliases collapse to a single dataset entry.
    z$CreateML 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 ú.z, which resolves to directory z#. Expected a path to an image file.)r   ÚresolveÚOSErrorÚ
ValueErrorÚparentsÚis_dirr   )r   r   Úimages_directory_resolvedÚ
image_pathÚresolved_image_pathÚexcs         út/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/supervision/dataset/formats/createml.pyÚ_resolve_image_pathr      s¥  € õ !%Ð%:Ñ ;Ô ;× CÒ CÑ EÔ EÐÝÐ+Ñ,Ô,­t°JÑ/?Ô/?Ñ?€JðØ(×0Ò0Ñ2Ô2ÐÐøÝ•ZÐ ð ð ð Ýð/°:ð /ð /Ø),ð/ð /ñ
ô 
ð ð	øøøøðøøøð
 Ð7Ò7Ð7ÝðP°:ð Pð Pà)ðPð Pð Pñ
ô 
ð 	
ð
 !Ð(;Ô(CÐCÐCÝð6°:ð 6ð 6Ø.ð6ð 6à2ð6ð 6ð 6ñ
ô 
ð 	
ð
 ×!Ò!Ñ#Ô#ð 
Ýð °:ð  ð  Ø%8ð ð  ð  ñ
ô 
ð 	
õ
 Ð"Ñ#Ô#Ð#s   ÁA ÁBÁ(A>Á>BÚimage_annotationsúlist[CreateMLDict]Úclass_to_indexúdict[str, int]r
   c           	     ó�  — | st          j        ¦   «         S g }g }| D ]ã}	 |d         }t          |d         ¦  «        }t          |d         ¦  «        }t          |d         ¦  «        }t          |d         ¦  «        }	|d         }
n/# t          t          f$ r}t          d|›d|› �¦  «        |‚d	}~ww xY w|                     ||d
z  z
  ||	d
z  z
  ||d
z  z   ||	d
z  z   g¦  «         |                     ||
         ¦  «         Œät          t          j        |t          j	        ¬¦  «        t          j        |t          ¬¦  «        ¬¦  «        S )a×  Convert a single image's CreateML annotations into ``Detections``.

    CreateML stores each box as a pixel-space centre point plus width/height
    (``{"x", "y", "width", "height"}``); they are converted to ``xyxy`` corners.

    Args:
        image_annotations: List of annotation dicts for one image, each containing
            a ``"label"`` key and a ``"coordinates"`` dict with ``"x"``, ``"y"``,
            ``"width"``, and ``"height"`` keys.
        class_to_index: Mapping from class name to zero-based integer id.

    Returns:
        A ``Detections`` instance with ``xyxy`` boxes and ``class_id`` set.
        Returns ``Detections.empty()`` when ``image_annotations`` is empty.

    Raises:
        ValueError: If an annotation is missing required keys (``"coordinates"``,
            ``"label"``, or any coordinate sub-key), or if a coordinate value
            cannot be converted to float.

    Example:
        ```pycon
        >>> from supervision.dataset.formats.createml import (
        ...     createml_annotations_to_detections,
        ... )
        >>> annotations = [
        ...     {
        ...         "label": "dog",
        ...         "coordinates": {"x": 50, "y": 50, "width": 20, "height": 20},
        ...     }
        ... ]
        >>> detections = createml_annotations_to_detections(annotations, {"dog": 0})
        >>> detections.xyxy
        array([[40., 40., 60., 60.]], dtype=float32)
        >>> detections.class_id
        array([0])

        ```
    ÚcoordinatesÚxÚyÚwidthÚheightÚlabelz$Malformed CreateML annotation entry z: Né   )Údtype)ÚxyxyÚclass_id)r
   ÚemptyÚfloatÚKeyErrorÚ	TypeErrorr   ÚappendÚnpÚarrayÚfloat32Úint)r   r!   r,   Ú	class_idsÚ
annotationr$   Úx_centerÚy_centerr'   r(   r)   r   s               r   Ú"createml_annotations_to_detectionsr;   9   sŒ  € ðT ð "ÝÔÑ!Ô!Ð!à€DØ€IØ'ð 0ð 0ˆ
ð
	Ø$ ]Ô3ˆKÝ˜[¨Ô-Ñ.Ô.ˆHÝ˜[¨Ô-Ñ.Ô.ˆHÝ˜+ gÔ.Ñ/Ô/ˆEÝ˜; xÔ0Ñ1Ô1ˆFØ˜wÔ'ˆEˆEøÝ�)Ð$ð 	ð 	ð 	ÝØL°zÐLÐLÀsÐLÐLñô àðøøøøð	øøøð 	�Šà˜5 1™9Ñ$Ø˜6 A™:Ñ%Ø˜5 1™9Ñ$Ø˜6 A™:Ñ%ð	ñ	
ô 	
ð 	
ð 	×Ò˜¨Ô.Ñ/Ô/Ð/Ð/åÝŒX�d¥"¤*Ð-Ñ-Ô-Ý”˜)­3Ð/Ñ/Ô/ðñ ô ð s   ŸA$BÂB0ÂB+Â+B0FÚannotations_pathÚshow_progressÚboolú2tuple[list[str], list[str], dict[str, Detections]]c                óÎ  — t          dt          |¬¦  «        ¦  «        }t          |t          ¦  «        s%t	          dt          |¦  «        j        › d�¦  «        ‚	 t          d„ |D ¦   «         ¦  «        }n,# t          t          f$ r}t	          d|› �¦  «        |‚d}~ww xY wd„ t          |¦  «        D ¦   «         }g }i }t          |d	| ¬
¦  «        D ]‘}	|	                     d¦  «        }
|
€t	          d|	›�¦  «        ‚t          | |
¬¦  «        }||v rt	          d|
›d�¦  «        ‚t          |	                     d¦  «        pg |¬¦  «        ||<   |                     |¦  «         Œ’|||fS )a[  Load CreateML object-detection annotations and convert them to ``Detections``.

    CreateML uses a single JSON file containing a list of per-image entries, each
    holding axis-aligned bounding boxes. Class names are inferred from the labels
    present in the file and assigned stable, sorted, zero-based ids. Because the
    format has no explicit category list, a class with no boxes anywhere in the
    file will not appear in the returned ``classes``.

    Args:
        images_directory_path: Path to the directory containing the images.
        annotations_path: Path to the CreateML JSON annotation file.
        show_progress: If ``True``, display a tqdm progress bar while loading
            annotations.

    Returns:
        A tuple of three elements:

        - ``classes`` (``list[str]``): globally sorted class names inferred from
          all labels present in the file.
        - ``image_paths`` (``list[str]``): canonical resolved path for every
          entry in the JSON, in file order.
        - ``annotations`` (``dict[str, Detections]``): mapping from canonical
          resolved image path to its ``Detections``.

    Raises:
        ValueError: If the JSON root is not a list.
        ValueError: If an entry is missing the required ``"image"`` key.
        ValueError: If an annotation is missing required coordinate or label keys.
        ValueError: If two entries resolve to the same image path.
        ValueError: If an annotation's ``image`` field resolves to the images
            directory itself or to a path outside it (e.g. via ``..`` traversal
            or an absolute path).
    r    )Ú	file_pathzCCreateML annotation file must contain a JSON list at the root, got r   c                óR   — h | ]$}|                      d ¦  «        pg D ]
}|d         ’ŒŒ%S )r   r)   )Úget)Ú.0Úentryr8   s      r   ú	<setcomp>z,load_createml_annotations.<locals>.<setcomp>µ   sU   € ð ð ð àØ#(§9¢9¨]Ñ#;Ô#;Ð#A¸rðð ð ð ˜7Ô#ðð ð ð ó    zEMalformed CreateML annotation entry (missing or non-string 'label'): Nc                ó   — i | ]\  }}||“Œ	S © rI   )rD   ÚindexÚ
class_names      r   ú
<dictcomp>z-load_createml_annotations.<locals>.<dictcomp>À   s   € ÐTÐTÐTÑ,=¨E°:�j %ÐTÐTÐTrG   zLoading CreateML annotations)ÚdescÚdisableÚimagez?CreateML annotation entry is missing the required 'image' key: )r   r   z>CreateML annotation file contains duplicate entries for image z&. Each image must appear at most once.r   )r   r!   )r   r   Ú
isinstanceÚlistr   ÚtypeÚ__name__Úsortedr0   r1   Ú	enumerater   rC   r   r;   r2   )r   r<   r=   Úcreateml_dataÚclassesr   r!   Úimage_pathsr   rE   r   r   s               r   Úload_createml_annotationsrY   „   s+  € õL Ø�nÐ7GÐHÑHÔHñô €Mõ �m¥TÑ*Ô*ð 
Ýð3Ý˜Ñ&Ô&Ô/ð3ð 3ð 3ñ
ô 
ð 	
ð
Ýðð à*ðñ ô ñ
ô 
ˆˆøõ •iÐ ð ð ð Ýð6Ø03ð6ð 6ñ
ô 
ð ð	øøøøðøøøð
 UÐTÅÈ7ÑASÔASÐTÑTÔT€Nà€KØ)+€KÝØØ+Ø!Ð!ðñ ô ð 'ð 'ˆð
 —Y’Y˜wÑ'Ô'ˆ
ØÐÝðØðð ñô ð õ )Ø"7ÀJð
ñ 
ô 
ˆ
ð ˜Ð$Ð$ÝðHØðHð Hð Hñô ð õ #EØ#Ÿiši¨Ñ6Ô6Ð<¸"Ø)ð#
ñ #
ô #
ˆ�JÑð 	×Ò˜:Ñ&Ô&Ð&Ð&à�K Ð,Ð,s   ÁA4 Á4BÂBÂBÚ
detectionsrW   ú	list[str]c           	     ó  — | j         }|€t          d¦  «        ‚g }t          | j        |¦  «        D ]S\  }}d„ |D ¦   «         \  }}}}	 |j        |t          |¦  «                 ||z   dz  ||	z   dz  ||z
  |	|z
  dœdœ¦  «         ŒT|S )a  Convert ``Detections`` into a list of CreateML annotation dicts.

    Each bounding box is stored as a pixel-space centre point plus width and
    height, which is the CreateML object-detection convention.

    Args:
        detections: The detections to convert. ``class_id`` must not be ``None``.
        classes: Ordered list of class names; ``detections.class_id`` values are
            used as indices into this list.

    Returns:
        A list of dicts, each with a ``"label"`` key (class name) and a
        ``"coordinates"`` dict containing ``"x"``, ``"y"``, ``"width"``, and
        ``"height"`` in pixel space.

    Raises:
        ValueError: If ``detections.class_id`` is ``None``.

    Example:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> from supervision.dataset.formats.createml import (
        ...     detections_to_createml_annotations,
        ... )
        >>> detections = sv.Detections(
        ...     xyxy=np.array([[40, 40, 60, 60]], dtype=np.float32),
        ...     class_id=np.array([0], dtype=int),
        ... )
        >>> detections_to_createml_annotations(detections, classes=["dog"])
        [{'label': 'dog', 'coordinates':
          {'x': 50.0, 'y': 50.0, 'width': 20.0, 'height': 20.0}}]

        ```
    NzXclass_id is required for CreateML export, but the provided Detections has class_id=None.c              3  ó4   K  — | ]}t          |¦  «        V — Œd S ©N)r/   )rD   Úvalues     r   ú	<genexpr>z5detections_to_createml_annotations.<locals>.<genexpr>  s(   è è € Ð%EÐ%E°u¥e¨E¡l¤lÐ%EÐ%EÐ%EÐ%EÐ%EÐ%ErG   r*   )r%   r&   r'   r(   )r)   r$   )r-   r   Úzipr,   r2   r6   )
rZ   rW   r7   r   r,   r-   Úx_minÚy_minÚx_maxÚy_maxs
             r   Ú"detections_to_createml_annotationsrf   à   sØ   € ðL Ô#€IØÐÝð,ñ
ô 
ð 	
ð ')€KÝ˜jœo¨yÑ9Ô9ð 
ð 
‰ˆˆhØ%EÐ%EÀÐ%EÑ%EÔ%EÑ"ˆˆu�e˜UØˆÔà ¥ X¡¤Ô/à %™-¨1Ñ,Ø %™-¨1Ñ,Ø" U™]Ø# e™mð	 ð  ðð ñ
	
ô 
	
ð 
	
ð 
	
ð ÐrG   Údatasetr   ÚNonec                óÒ   ‡ — t          ‰ j        d„ d¬¦  «         t          |¦  «        j                             dd¬¦  «         ˆ fd„‰ j        D ¦   «         }t          ||¬¦  «         dS )	a�  Export a ``DetectionDataset`` to a CreateML object-detection JSON file.

    Only the filename component of each image path is stored in the JSON (e.g.
    ``"img.jpg"`` rather than ``"/data/train/img.jpg"``). This matches CreateML
    convention and means the loader reconstructs paths relative to
    ``images_directory_path``. As a consequence, two images with the same
    basename from different directories would collapse to the same ``"image"``
    key, so the exporter rejects that case before writing.

    Args:
        dataset: The ``DetectionDataset`` to write.
        annotations_path: Output path for the CreateML JSON file. Parent
            directories are created if they do not already exist.

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

    Example:
        ```python
        import supervision as sv
        from supervision.dataset.formats.createml import save_createml_annotations

        dataset = sv.DetectionDataset(classes=["dog"], images=[], annotations={})
        save_createml_annotations(dataset, "/tmp/annotations.json")
        ```
    c                ó*   — t          | ¦  «        j        S r^   )r   Úname)r   s    r   ú<lambda>z+save_createml_annotations.<locals>.<lambda>>  s   € �t JÑ/Ô/Ô4€ rG   zCreateML image)rX   ÚkeyÚoutput_kindT)r   Úexist_okc                ó|   •— g | ]8}t          |¦  «        j        t          ‰j        |         ‰j        ¬ ¦  «        dœ‘Œ9S ))rZ   rW   )rO   r   )r   rk   rf   r   rW   )rD   r   rg   s     €r   ú
<listcomp>z-save_createml_annotations.<locals>.<listcomp>B  sa   ø€ ð )ð )ð )ð õ ˜*Ñ%Ô%Ô*Ý=Ø"Ô.¨zÔ:ÀGÄOðñ ô ð	
ð 	
ð)ð )ð )rG   )ÚdatarA   N)r	   rX   r   ÚparentÚmkdirr   )rg   r<   rV   s   `  r   Úsave_createml_annotationsru     s¨   ø€ õ> !ØÔ'Ø4Ð4Ø$ðñ ô ð õ
 	Ð	ÑÔÔ!×'Ò'°¸tÐ'ÑDÔDÐDð)ð )ð )ð )ð "Ô-ð)ñ )ô )€Mõ ØØ"ðñ ô ð ð ð rG   )r   r   r   r   r   r   )r   r    r!   r"   r   r
   )F)r   r   r<   r   r=   r>   r   r?   )rZ   r
   rW   r[   r   r    )rg   r   r<   r   r   rh   )Ú
__future__r   Úpathlibr   Útypingr   r   r   Únumpyr3   Ú	tqdm.autor   Úsupervision.dataset.utilsr	   Úsupervision.detection.corer
   Úsupervision.utils.filer   r   Úsupervision.dataset.corer   Údictr   ÚCreateMLDictr   r;   rY   rf   ru   rI   rG   r   ú<module>r�      sM  ðØ "Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ð Ð Ø +Ð +Ð +Ð +Ð +Ð +Ð +Ð +Ð +Ð +à Ð Ð Ð Ø Ð Ð Ð Ð Ð à BÐ BÐ BÐ BÐ BÐ BØ 1Ð 1Ð 1Ð 1Ð 1Ð 1Ø AÐ AÐ AÐ AÐ AÐ AÐ AÐ Aàð :Ø9Ð9Ð9Ð9Ð9Ð9à�C˜�HŒ~€ð#$ð #$ð #$ð #$ðLHð Hð Hð Hð\  ðY-ð Y-ð Y-ð Y-ð Y-ðx:ð :ð :ð :ðz1ð 1ð 1ð 1ð 1ð 1rG   