§
    ­¸j4Á  ã                  ó   — d Z ddlmZ ddlZddlmZ ddlmZ ddlm	Z	 	 ddl
Zn# e$ r dZY nw xY wddlZddlZddlZddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZmZ ddlmZ ddl m!Z!  e!¦   «         Z" G d„ d¦  «        Zh d£ez  Z# e$h d£¦  «        Z%dZ&ed$d„¦   «         Z'd%d„Z(d&d„Z)ed'd „¦   «         Z*d(d!„Z+ G d"„ d#¦  «        Z,dS ))z7Transforms and data augmentation for both image + bbox.é    )ÚannotationsN)ÚSequence)Úcache)ÚAny)ÚNDArray)ÚImage)ÚTensor)Ú	Normalize)ÚD4_ALIAS_NAMESÚHFLIP_TRANSFORM_NAMESÚHORIZONTAL_FLIP_ALIAS_NAMESÚIMAGE_LEVEL_TARGET_FIELDSÚ#filter_keypoint_hflip_augmentations)Úbox_xyxy_to_cxcywh)Ú
get_loggerc                  ó&   — e Zd Z	 	 ddd„Zddd„Zd	S )r
   ©g
×£p=
ß?gÉv¾Ÿ/Ý?g–C‹lçûÙ?©gZd;ßOÍ?gyé&1¬Ì?gÍÌÌÌÌÌÌ?Úmeanútuple[float, ...]ÚstdÚreturnÚNonec                ó0   — t          ||¦  «        | _        d S ©N)Ú_TVNormalizeÚ
_normalize)Úselfr   r   s      új/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/datasets/transforms.pyÚ__init__zNormalize.__init__2   s   € õ
 ' t¨SÑ1Ô1ˆŒˆˆó    NÚimager	   Útargetúdict[str, Any] | Noneú$tuple[Tensor, dict[str, Any] | None]c                ó˜  — |                       |¦  «        }|€|dfS |                     ¦   «         }|j        dd…         \  }}d|v rC|d         }t          |¦  «        }|t	          j        ||||gt          j        ¬¦  «        z  }||d<   d|v r;|d                              ¦   «         }|d         |z  |d<   |d         |z  |d<   ||d<   ||fS )a—  Normalize image and convert target coordinates to relative format.

        Applies ImageNet-style channel normalization to the image, then converts
        bounding boxes from absolute xyxy pixel coordinates to normalized cxcywh
        format (divided by ``[w, h, w, h]``) and scales keypoint x/y by image
        width/height respectively.

        Args:
            image: CHW float tensor to normalize.
            target: Optional dict with keys ``"boxes"`` (xyxy pixel coords,
                shape ``[N, 4]``) and/or ``"keypoints"`` (shape ``[N, K, 3]``
                where the third channel is visibility). Mutated copy returned;
                original is not modified.

        Returns:
            Tuple of ``(normalized_image, target)`` where ``target`` has boxes
            in normalized cxcywh format and keypoints scaled to ``[0, 1]``, or
            ``(normalized_image, None)`` when ``target`` is ``None``.

        Examples:
            >>> import torch
            >>> normalize = Normalize()
            >>> img = torch.zeros(3, 64, 64)
            >>> out_img, out_tgt = normalize(img, None)
            >>> out_tgt is None
            True
        NéþÿÿÿÚboxes©ÚdtypeÚ	keypoints).r   ).é   )r   ÚcopyÚshaper   ÚtorchÚtensorÚfloat32Úclone)r   r"   r#   ÚhÚwr(   r+   s          r   Ú__call__zNormalize.__call__9   sï   € ð8 —’ Ñ&Ô&ˆØˆ>Ø˜$�;ÐØ—’‘”ˆØŒ{˜2˜3˜3Ô‰ˆˆ1Ø�fÐÐØ˜7”OˆEÝ& uÑ-Ô-ˆEØ�EœL¨!¨Q°°1¨½U¼]ÐKÑKÔKÑKˆEØ#ˆF�7‰OØ˜&Ð Ð Ø˜{Ô+×1Ò1Ñ3Ô3ˆIØ )¨&Ô 1°AÑ 5ˆI�fÑØ )¨&Ô 1°AÑ 5ˆI�fÑØ"+ˆF�;ÑØ�fˆ}Ðr!   )r   r   )r   r   r   r   r   r   r   )r"   r	   r#   r$   r   r%   )Ú__name__Ú
__module__Ú__qualname__r    r5   © r!   r   r
   r
   1   sN   € € € € € ð #8Ø!6ð2ð 2ð 2ð 2ð 2ð+ð +ð +ð +ð +ð +ð +r!   r
   >#   ÚPadÚCropÚAffineÚResizeÚRotateÚ	DownscaleÚ	TransposeÚ
CenterCropÚ
CropAndPadÚ
RandomCropÚ
SafeRotateÚPadIfNeededÚPerspectiveÚRandomScaleÚVerticalFlipÚGridDistortionÚLongestMaxSizeÚRandomRotate90ÚPiecewiseAffineÚRandomSizedCropÚSmallestMaxSizeÚThinPlateSplineÚElasticTransformÚShiftScaleRotateÚGridElasticDeformÚOpticalDistortionÚRandomGridShuffleÚRandomResizedCropÚBBoxSafeRandomCropÚRandomCropNearBBoxÚCappedLongestMaxSizeÚRandomCropFromBordersÚRandomSizedBBoxSafeCropÚAtLeastOneBBoxRandomCropÚCropNonEmptyMaskIfExists>   ÚOneOfÚSomeOfÚ
SequentialrX   r   Útypec                 ó6   —  G d„ dt           j        ¦  «        } | S )uí  Build a ``LongestMaxSize`` subclass that only shrinks, never upscales.

    Standard ``alb.LongestMaxSize`` always forces the longest side to exactly ``max_size``, scaling the image up
    when its current longest side is smaller than the target. Chained after ``SmallestMaxSize`` (as in RF-DETR's
    non-square training resize), this silently inflates every image whose aspect ratio keeps the long side below
    ``max_size`` â€” the common case, since ``max_size`` defaults to the DETR-style 1333 cap while typical training
    resolutions are far smaller.

    This subclass clamps the resolved scale factor to ``<= 1.0``, giving it torchvision
    ``RandomResize``-style conditional-cap semantics: a no-op when the image already fits within ``max_size``, a
    shrink when it doesn't. Lazily defined (not at module scope) so importing this module never requires
    Albumentations to be installed.

    Returns:
        A ``LongestMaxSize`` subclass with capped (never-upscale) resize behaviour.
    c                  ó    ‡ — e Zd Zdˆ fd„Zˆ xZS )ú:_capped_longest_max_size_cls.<locals>.CappedLongestMaxSizeÚparamsúdict[str, Any]Údatar   c                ó~   •— t          ¦   «                              ||¦  «        }t          |d         d¦  «        |d<   |S )NÚscaleç      ð?)ÚsuperÚget_params_dependent_on_dataÚmin)r   rd   rf   ÚresolvedÚ	__class__s       €r   rk   zW_capped_longest_max_size_cls.<locals>.CappedLongestMaxSize.get_params_dependent_on_data³   s;   ø€ Ý',¡w¤w×'KÒ'KÈFÐTXÑ'YÔ'YˆHÝ # H¨WÔ$5°sÑ ;Ô ;ˆH�WÑØˆOr!   )rd   re   rf   re   r   re   )r6   r7   r8   rk   Ú__classcell__)rn   s   @r   rX   rc   ²   s=   ø€ € € € € ð	ð 	ð 	ð 	ð 	ð 	ð 	ð 	ð 	ð 	r!   rX   )ÚalbrJ   )rX   s    r   Ú_capped_longest_max_size_clsrq   Ÿ   s7   € ð&ð ð ð ð �sÔ1ñ ô ð ð  Ðr!   Ú	transformúalb.BasicTransformÚboolc                óœ   — t          | ¦  «        j        t          v rdS t          | d¦  «        rt	          d„ | j        D ¦   «         ¦  «        S dS )a÷  Return True if transform (or any nested transform) affects spatial coordinates.

    For container transforms such as ``A.OneOf`` or ``A.Sequential``, returns ``True`` when *any* nested transform is
    geometric so that bounding-box handling is enabled for the whole container.

    Args:
        transform: Albumentations transform to inspect.

    Returns:
        ``True`` if the transform modifies spatial layout; ``False`` otherwise.

    Examples:
        >>> from albumentations import GaussianBlur, HorizontalFlip, OneOf
        >>> _is_geometric_transform(HorizontalFlip())
        True
        >>> _is_geometric_transform(GaussianBlur())
        False
        >>> _is_geometric_transform(OneOf([HorizontalFlip(), GaussianBlur()]))
        True
    TÚ
transformsc              3  ó4   K  — | ]}t          |¦  «        V — Œd S r   )Ú_is_geometric_transform)Ú.0Úts     r   ú	<genexpr>z*_is_geometric_transform.<locals>.<genexpr>Ô   s+   è è € ÐLÐL°!Õ*¨1Ñ-Ô-ÐLÐLÐLÐLÐLÐLr!   F)r`   r6   ÚGEOMETRIC_TRANSFORMSÚhasattrÚanyrv   )rr   s    r   rx   rx   »   sV   € õ* ˆI�„ÔÕ#7Ð7Ð7Øˆtåˆy˜,Ñ'Ô'ð MÝÐLÐL°yÔ7KÐLÑLÔLÑLÔLÐLØˆ5r!   ÚnameÚstrrd   re   c           	     óî  — t           €t          d¦  «        ‚| t          v �rü|                     dg ¦  «        }t	          |t
          ¦  «        s't          d| › dt          |¦  «        j        › �¦  «        ‚g }|D ]Ì}t	          |t          ¦  «        rt          |¦  «        dk    rt          d|›�¦  «        ‚t          t          |                     ¦   «         ¦  «        ¦  «        \  }}t	          |t          ¦  «        s't          d|› d	t          |¦  «        j        › �¦  «        ‚|                     t          ||¦  «        ¦  «         ŒÍ| d
k    rF|st          d¦  «        ‚d„ |                     ¦   «         D ¦   «         }|                     dd¦  «         nY| dk    r5d„ |                     ¦   «         D ¦   «         }|                     dd¦  «         nd„ |                     ¦   «         D ¦   «         }t#          t           | d¦  «        }|€t          d| ›�¦  «        ‚ |dd|i|¤ŽS | t$          k    rt'          ¦   «         nt#          t           | d¦  «        }	|	€t          d| ›�¦  «        ‚ |	di t)          | ||	¦  «        ¤ŽS )af  Build a single Albumentations transform from its name and parameter dict.

    Handles container transforms (``OneOf``, ``SomeOf``, ``Sequential``) by recursively building the nested
    ``transforms`` list.  Leaf transforms are instantiated directly from the ``albumentations`` namespace.

    For ``OneOf`` and ``Sequential``, the container-level ``p`` is respected when
    explicitly provided. When omitted, RF-DETR defaults it to ``1.0`` to preserve
    existing behavior. For ``OneOf``, which child is applied (when the container fires)
    is determined by the children's own ``p`` values; at least one nested transform is required.
    ``Sequential`` runs all transforms in order when the container fires.

    Args:
        name: Transform name (e.g. ``"HorizontalFlip"``, ``"OneOf"``).
        params: Parameter dictionary for the transform.  For container transforms
            the dict must contain a ``"transforms"`` key whose value is a list of single-key dicts ``{name: params}``.

    Returns:
        Instantiated Albumentations transform.

    Raises:
        ImportError: If Albumentations is not installed.
        ValueError: If ``name`` is unknown or ``params`` is malformed.

    Examples:
        >>> from albumentations import HorizontalFlip, OneOf
        >>> t = _build_albu_transform("HorizontalFlip", {"p": 0.5})
        >>> isinstance(t, HorizontalFlip)
        True
        >>> container = _build_albu_transform(
        ...     "OneOf",
        ...     {"transforms": [{"HorizontalFlip": {"p": 1.0}}, {"VerticalFlip": {"p": 1.0}}]},
        ... )
        >>> isinstance(container, OneOf)
        True
    NúxCustom Albumentations augmentations require the optional augmentation extra. Install with: pip install 'rfdetr[augment]'rv   ú'z!.transforms' must be a list, got r,   z;Each nested transform entry must be a single-key dict, got z!Parameters for nested transform 'z' must be a dict, got r]   z''OneOf' requires at least one transformc                ó&   — i | ]\  }}|d k    ¯||“ŒS ©rv   r9   ©ry   ÚkÚvs      r   ú
<dictcomp>z)_build_albu_transform.<locals>.<dictcomp>  ó(   € ÐQÐQÐQ¡T Q¨¸qÀLÒ?PÐ?P˜A˜qÐ?PÐ?PÐ?Pr!   Úpri   r_   c                ó&   — i | ]\  }}|d k    ¯||“ŒS r…   r9   r†   s      r   r‰   z)_build_albu_transform.<locals>.<dictcomp>  rŠ   r!   c                ó&   — i | ]\  }}|d k    ¯||“ŒS r…   r9   r†   s      r   r‰   z)_build_albu_transform.<locals>.<dictcomp>  rŠ   r!   z"Unknown Albumentations container: z"Unknown Albumentations transform: r9   )rp   ÚImportErrorÚALBUMENTATIONS_CONTAINERSÚgetÚ
isinstanceÚlistÚ
ValueErrorr`   r6   ÚdictÚlenÚnextÚiterÚitemsÚappendÚ_build_albu_transformÚ
setdefaultÚgetattrÚ_CAPPED_LONGEST_MAX_SIZE_NAMErq   Ú_normalize_albu_params)
r   rd   Ú
raw_nestedÚnested_transformsÚentryÚnested_nameÚnested_paramsÚother_paramsÚcontainer_clsÚaug_clss
             r   rš   rš   Ø   sÆ  € õH €{Ýð:ñ
ô 
ð 	
ð
 Õ(Ð(Ñ(Ø—Z’Z ¨bÑ1Ô1ˆ
Ý˜*¥dÑ+Ô+ð 	eÝÐc ÐcÐcÍÈZÑHXÔHXÔHaÐcÐcÑdÔdÐdØ68ÐØð 		Xð 		XˆEÝ˜e¥TÑ*Ô*ð j­c°%©j¬j¸Aªo¨oÝ Ð!hÐ_dÐ!hÐ!hÑiÔiÐiÝ)-­d°5·;²;±=´=Ñ.AÔ.AÑ)BÔ)BÑ&ˆK˜Ý˜m­TÑ2Ô2ð Ý ð:¸ð :ð :Ý Ñ.Ô.Ô7ð:ð :ñô ð ð ×$Ò$Õ%:¸;ÈÑ%VÔ%VÑWÔWÐWÐWà�7Š?ˆ?Ø$ð LÝ Ð!JÑKÔKÐKØQÐQ¨V¯\ª\©^¬^ÐQÑQÔQˆLØ×#Ò# C¨Ñ-Ô-Ð-Ð-Ø�\Ò!Ð!ØQÐQ¨V¯\ª\©^¬^ÐQÑQÔQˆLØ×#Ò# C¨Ñ-Ô-Ð-Ð-àQÐQ¨V¯\ª\©^¬^ÐQÑQÔQˆLå¥ T¨4Ñ0Ô0ˆØÐ ÝÐJÀ$ÐJÐJÑKÔKÐKØˆ}ÐJÐJÐ(9ÐJ¸\ÐJÐJÐJà04Õ8UÒ0UÐ0UÕ*Ñ,Ô,Ð,Õ[bÕcfÐhlÐnrÑ[sÔ[s€GØ€ÝÐF¸dÐFÐFÑGÔGÐGØˆ7ÐCÐCÕ+¨D°&¸'ÑBÔBÐCÐCÐCr!   r¦   c                ó<   — t          j        | ¦  «        }d|j        v S )a  Return whether ``RandomSizedCrop`` expects a ``size`` keyword.

    The Albumentations 2.x API changed ``RandomSizedCrop`` from separate ``height``/``width`` parameters to a single
    ``size=(height, width)`` parameter. This helper caches the signature check per class so repeated transform
    construction during dataset setup does not repeat introspection.

    Args:
        aug_cls: Albumentations transform class to inspect.

    Returns:
        ``True`` when the class accepts a ``size`` keyword argument; otherwise ``False``.
    Úsize)ÚinspectÚ	signatureÚ
parameters)r¦   rª   s     r   Ú"_random_sized_crop_uses_size_paramr¬   (  s"   € õ Ô! 'Ñ*Ô*€IØ�YÔ)Ð)Ð)r!   c                ó¤  — t          |¦  «        }| dk    r|S t          |¦  «        }|r–d|v }d|v }d|v }|r.|                     dd¦  «         |                     dd¦  «         |S |r5|r3|                     d¦  «        }|                     d¦  «        }	||	f|d<   |S ||k    r|r|sdnd}
t          d|
› d�¦  «        ‚|S |s�d|v r‹|                     d¦  «        }t          |t          ¦  «        rat          |¦  «        dk    rN|                     d|d	         ¦  «         |                     d|d
         ¦  «         |                     dd¦  «         |S )aœ  Normalize transform params across Albumentations API variations.

    Currently this adapts ``RandomSizedCrop`` arguments so a config using ``height``/``width`` works on Albumentations
    2.x and a config using ``size=(height, width)`` still works on Albumentations 1.x.

    Args:
        name: Albumentations transform name.
        params: Raw transform parameter mapping from config.
        aug_cls: Albumentations transform class that will be instantiated.

    Returns:
        A normalized copy of ``params`` suitable for the installed Albumentations version.

    Examples:
        >>> class CropV2:
        ...     def __init__(self, *, size, min_max_height): ...
        >>> _normalize_albu_params(
        ...     "RandomSizedCrop",
        ...     {"min_max_height": [384, 600], "height": 640, "width": 640},
        ...     CropV2,
        ... )
        {'min_max_height': [384, 600], 'size': (640, 640)}
    rM   r¨   ÚheightÚwidthNz˜RandomSizedCrop for the installed Albumentations version expects 'size=(height, width)'. Received only one of 'height'/'width' without 'size' (missing 'z').é   r   r,   )	r”   r¬   Úpopr“   r�   r‘   r   r•   r›   )r   rd   r¦   Únormalized_paramsÚ	uses_sizeÚhas_sizeÚ
has_heightÚ	has_widthr®   r¯   Úmissingr¨   s               r   rž   rž   :  sË  € õ0 ˜V™œÐØÐ Ò Ð Ø Ð å2°7Ñ;Ô;€Iàð #!ð Ð.Ð.ˆØÐ!2Ð2ˆ
ØÐ0Ð0ˆ	àð 	%ð ×!Ò! (¨DÑ1Ô1Ð1Ø×!Ò! '¨4Ñ0Ô0Ð0Ø$Ð$àð 	%˜)ð 	%Ø&×*Ò*¨8Ñ4Ô4ˆFØ%×)Ò)¨'Ñ2Ô2ˆEØ)/°¨Ð˜fÑ%Ø$Ð$à˜Ò"Ð"ð ",ÐK°IÐK�g�gÀ8ˆGÝð9à,3ð9ð 9ð 9ñô ð ð !Ð ð ð 0˜Ð#4Ð4Ð4Ø ×$Ò$ VÑ,Ô,ˆÝ�d�HÑ%Ô%ð 	0­#¨d©)¬)°qª.¨.Ø×(Ò(¨°4¸´7Ñ;Ô;Ð;Ø×(Ò(¨°$°q´'Ñ:Ô:Ð:ð ×!Ò! &¨$Ñ/Ô/Ð/àÐr!   c                  ó   — e Zd ZdZd6d7d	„Zd8d„Zed9d„¦   «         Zed:d„¦   «         Zed;d„¦   «         Z	ed<d„¦   «         Z
e	 	 d=d>d#„¦   «         Zed?d%„¦   «         Zed@d&„¦   «         ZdAd+„ZdBd0„Ze	 	 d=dCd5„¦   «         ZdS )DÚAlbumentationsWrappera,	  Wrapper to apply Albumentations transforms to (image, target) tuples.

    This wrapper integrates Albumentations transforms with RF-DETR's data pipeline, automatically handling bounding box
    and segmentation mask transformations for geometric augmentations while preserving the (image, target) tuple format.

    The wrapper automatically detects transform types:
    - **Geometric transforms** (flips, rotations, crops): Bounding boxes and instance
      masks are transformed along with the image to maintain correct object localization.
    - **Pixel-level transforms** (blur, color adjustments, noise): Bounding boxes and
      masks remain unchanged as only pixel values are modified.

    Detection checks the transform class name against ``GEOMETRIC_TRANSFORMS`` and recursively inspects nested container
    transforms (for example ``OneOf`` and ``Sequential``). For geometric transforms, bbox_params are automatically
    configured to handle coordinate transformations, clip boxes to image boundaries, and remove invalid boxes.

    Args:
        transform: Albumentations transform to apply (e.g., alb.HorizontalFlip, alb.GaussianBlur).
        keypoint_flip_pairs: Joint index pairs for left/right swapping after a horizontal flip.
            ``None`` (default) means a detection pipeline -- no keypoint handling.
            An empty list ``[]`` marks a keypoint pipeline without semantic flip
            pairs, so horizontal-flip transforms should have been stripped from
            config before this point.

    Examples:
        >>> from albumentations import GaussianBlur, HorizontalFlip
        >>> # Geometric transform - automatically transforms boxes
        >>> wrapper = AlbumentationsWrapper(HorizontalFlip(p=1.0))
        >>> image = Image.new("RGB", (300, 400))
        >>> target = {"boxes": torch.tensor([[10, 20, 100, 200]]), "labels": torch.tensor([1])}
        >>> aug_image, aug_target = wrapper(image, target)

        >>> # Pixel-level transform - automatically preserves boxes
        >>> wrapper = AlbumentationsWrapper(GaussianBlur(p=1.0))
        >>> aug_image, aug_target = wrapper(image, target)

    Note:
        For custom geometric transforms, add the transform class name to the GEOMETRIC_TRANSFORMS set at module level.

    Raises:
        ImportError: If Albumentations is not installed.
    Nrr   rs   Úkeypoint_flip_pairsúlist[int] | Noner   r   c           	     ó:  — t           €t          d¦  «        ‚t          |¦  «        | _        t	          |pg ¦  «        | _        | j        r¹t          | j        ¦  «        }|r/t          t           d¦  «        st           	                    d¦  «         |r!t          t           d¦  «        rt           j
        nt           j        } ||gt          j        dddgdd¬	¦  «        t          j        d
g d¢d¬¦  «        ¬¦  «        | _        d S t          j        |g¦  «        | _        d S )Nr‚   ÚReplayComposez€albumentations.ReplayCompose not available; horizontal-flip keypoint slot swapping is disabled. Upgrade albumentations to >=1.3.Ú
pascal_vocÚcategory_idsÚidxsg        T)ÚformatÚlabel_fieldsÚmin_visibilityÚclipÚxy)Úkeypoint_instance_idsÚkeypoint_point_idsÚkeypoint_visibilityF)rÁ   rÂ   Úremove_invisible)Úbbox_paramsÚkeypoint_params)rp   rŽ   rx   Ú_is_geometricr’   Ú_keypoint_flip_pairsrt   r}   ÚloggerÚwarningr½   ÚComposeÚ
BboxParamsÚKeypointParamsrr   )r   rr   rº   Úneeds_replayÚcompose_clss        r   r    zAlbumentationsWrapper.__init__º  sD  € Ýˆ;Ýð>ñô ð õ 5°YÑ?Ô?ˆÔÝ$(Ð)<Ð)BÀÑ$CÔ$CˆÔ!àÔð 	6õ   Ô 9Ñ:Ô:ˆLØð ¥G­C°Ñ$AÔ$Að Ý—’ðRñô ð ð 1=ÐpÅÍÈoÑA^ÔA^Ðp�#Ô+Ð+ÕehÔepˆKØ(˜[Ø�ÝœNØ'Ø"0°&Ð!9Ø#&Øð	ñ ô õ !$Ô 2ØØ!gÐ!gÐ!gØ%*ð!ñ !ô !ðñ ô ˆDŒNˆNˆNõ" !œ[¨)¨Ñ5Ô5ˆDŒNˆNˆNr!   r€   c                ód  — d}t          | j        t          j        ¦  «        r.| j        j        D ] }t          |t          j        ¦  «        r|} nŒ!n&t          | j        t          j        ¦  «        r| j        }|€t                               | ¦  «        S | j        rdnd}| j	        j
        › d|› d|› d�S )z—Return a readable string representation of the wrapper.

        Returns:
            Representation including the wrapped transform and type.
        NÚ	geometriczpixel-levelz(transform=z, type=ú))r‘   rr   rp   rÐ   rv   ÚBasicTransformÚobjectÚ__repr__rÌ   rn   r6   )r   rr   Ú	candidateÚtransform_types       r   rÚ   zAlbumentationsWrapper.__repr__â  sÅ   € ð ˆ	Ý�d”n¥c¤kÑ2Ô2ð 	'Ø!œ^Ô6ð ð �	Ý˜i­Ô);Ñ<Ô<ð Ø )�IØ�Eðøõ ˜œ­Ô(:Ñ;Ô;ð 	'ØœˆIàÐÝ—?’? 4Ñ(Ô(Ð(à(,Ô(:ÐM˜˜ÀˆØ”.Ô)ÐYÐY°iÐYÐYÈÐYÐYÐYÐYr!   r(   úTensor | NDArray[Any]úNDArray[Any]c                ó"  — t          j        | ¦  «        r&|                      ¦   «                              ¦   «         nt	          j        | ¦  «        }t          |j        ¦  «        dk    s|j        d         dk    rt          d|j        › �¦  «        ‚|S )zÞConvert boxes to numpy array and validate shape.

        >>> import torch
        >>> boxes = torch.tensor([[10.0, 20.0, 30.0, 40.0]])
        >>> AlbumentationsWrapper._boxes_to_numpy(boxes).shape
        (1, 4)
        r°   r,   é   z"boxes must have shape (N, 4), got ©	r/   Ú	is_tensorÚcpuÚnumpyÚnpÚarrayr•   r.   r“   )r(   Úboxes_nps     r   Ú_boxes_to_numpyz%AlbumentationsWrapper._boxes_to_numpy÷  s}   € õ +0¬/¸%Ñ*@Ô*@ÐU�5—9’9‘;”;×$Ò$Ñ&Ô&Ð&ÅbÄhÈuÁoÄoˆÝˆxŒ~ÑÔ !Ò#Ð# x¤~°aÔ'8¸AÒ'=Ð'=ÝÐRÀ(Ä.ÐRÐRÑSÔSÐSØˆr!   r+   Ú	num_boxesÚintc                ó„  — t          j        | ¦  «        r&|                      ¦   «                              ¦   «         nt	          j        | ¦  «        }t          |j        ¦  «        dk    s|j        d         dk    rt          d|j        › �¦  «        ‚|j        d         |k    r t          d|› d|j        d         › �¦  «        ‚|S )zïConvert keypoints to numpy array and validate shape.

        >>> import torch
        >>> keypoints = torch.tensor([[[10.0, 20.0, 2.0]]])
        >>> AlbumentationsWrapper._keypoints_to_numpy(keypoints, 1).shape
        (1, 1, 3)
        é   r°   z)keypoints must have shape (N, K, 3), got r   z6keypoints first dimension must match number of boxes (z), got rá   )r+   ré   Úkeypoints_nps      r   Ú_keypoints_to_numpyz)AlbumentationsWrapper._keypoints_to_numpy  sÊ   € õ 38´/À)Ñ2LÔ2LÐe�y—}’}‘”×,Ò,Ñ.Ô.Ð.ÕRTÔRZÐ[dÑReÔReˆÝˆ|Ô!Ñ"Ô" aÒ'Ð'¨<Ô+=¸aÔ+@ÀAÒ+EÐ+EÝÐ]ÈÔI[Ð]Ð]Ñ^Ô^Ð^ØÔ˜aÔ  IÒ-Ð-ÝØrÈÐrÐrÐ[gÔ[mÐnoÔ[pÐrÐrñô ð ð Ðr!   rí   rÀ   ú	list[int]re   c                ó¾  — g }g }g }g }|D ]Ì}t          | |         ¦  «        D ]´\  }}|                     ¦   «         \  }	}
}|                     t          |	¦  «        t          |
¦  «        f¦  «         |                     t          |¦  «        ¦  «         |                     t          |¦  «        ¦  «         |                     t          |¦  «        ¦  «         ŒµŒÍ||||dœS )a<  Flatten per-instance keypoints into Albumentations keypoint fields.

        >>> keypoints = np.array([[[10.0, 20.0, 2.0], [0.0, 0.0, 0.0]]], dtype=np.float32)
        >>> fields = AlbumentationsWrapper._build_albu_keypoints(keypoints, [0])
        >>> fields["keypoints"]
        [(10.0, 20.0), (0.0, 0.0)]
        ©r+   rÆ   rÇ   rÈ   )Ú	enumerateÚtolistr™   Úfloat)rí   rÀ   Úalbu_keypointsÚinstance_idsÚ	point_idsÚ
visibilityÚoriginal_idxÚ	point_idxÚpointÚxÚyÚvisibles               r   Ú_build_albu_keypointsz+AlbumentationsWrapper._build_albu_keypoints  s÷   € ð 57ˆØ$&ˆØ!#ˆ	Ø"$ˆ
Ø ð 	2ð 	2ˆLÝ$-¨l¸<Ô.HÑ$IÔ$Ið 2ð 2Ñ �	˜5Ø %§¢¡¤‘��1�gØ×%Ò%¥u¨Q¡x¤xµ°q±´Ð&:Ñ;Ô;Ð;Ø×#Ò#¥E¨,Ñ$7Ô$7Ñ8Ô8Ð8Ø× Ò ¥ yÑ!1Ô!1Ñ2Ô2Ð2Ø×!Ò!¥%¨¡.¤.Ñ1Ô1Ð1Ð1ð2ð (Ø%1Ø"+Ø#-ð	
ð 
ð 	
r!   Úreplayr   rt   c           	     ó¶  — t          | t          ¦  «        sdS |                      d¦  «        }t          |t          ¦  «        rt	          d„ |D ¦   «         ¦  «        S |                      dd¦  «        sdS t          |                      dd¦  «        ¦  «                             dd¦  «        d	         }|t          v rd
S |dk    rR|                      d¦  «        pi }t          |                     d|                     dd	¦  «        ¦  «        ¦  «        dk    S |t          v r=|                      d¦  «        pi }t          |                     d¦  «        ¦  «        dk    S dS )a  Return whether Albumentations replay metadata applied a horizontal flip.

        Args:
            replay: ``ReplayCompose`` metadata from an Albumentations call.

        Returns:
            ``True`` only when a horizontal mirror transform was actually applied.
        Frv   c              3  óJ   K  — | ]}t                                |¦  «        V — Œd S r   )r¹   Ú _replay_contains_horizontal_flip)ry   rr   s     r   r{   zIAlbumentationsWrapper._replay_contains_horizontal_flip.<locals>.<genexpr>D  s2   è è € ÐuÐuÐ]fÕ,×MÒMÈiÑXÔXÐuÐuÐuÐuÐuÐur!   ÚappliedÚ__class_fullname__Ú ú.r,   éÿÿÿÿTÚFliprd   ÚaxisÚdÚgroup_elementr3   )
r‘   r”   r�   r’   r~   r€   Úrsplitr   rê   r   )r   rv   Útransform_namerd   s       r   r  z6AlbumentationsWrapper._replay_contains_horizontal_flip5  sP  € õ ˜&¥$Ñ'Ô'ð 	Ø�5à—Z’Z Ñ-Ô-ˆ
Ý�j¥$Ñ'Ô'ð 	vÝÐuÐuÐjtÐuÑuÔuÑuÔuÐuà�zŠz˜) UÑ+Ô+ð 	Ø�5å˜VŸZšZÐ(<¸bÑAÔAÑBÔB×IÒIÈ#ÈqÑQÔQÐRTÔUˆØÕ8Ð8Ð8Ø�4Ø˜VÒ#Ð#Ø—Z’Z Ñ)Ô)Ð/¨RˆFÝ�v—z’z &¨&¯*ª*°S¸"Ñ*=Ô*=Ñ>Ô>Ñ?Ô?À1ÒDÐDØ�^Ð+Ð+Ø—Z’Z Ñ)Ô)Ð/¨RˆFÝ�v—z’z /Ñ2Ô2Ñ3Ô3°sÒ:Ð:Øˆur!   FÚ	augmentedÚ	kept_idxsÚ
flip_pairsÚdid_flipr	   c                ó®  ‡— |j         d         }t          j        t          |¦  «        |dft          j        ¬¦  «        }d„ t          |¦  «        D ¦   «         Š| d         j         dd…         \  }}|                      dg ¦  «        }	|	�r«|                      d	g ¦  «        }
|                      d
g ¦  «        }|                      dg ¦  «        }t          j        d„ |	D ¦   «         t          j        ¬¦  «        }t          j        ˆfd„|
D ¦   «         t          j	        ¬¦  «        }t          j        d„ |D ¦   «         t          j	        ¬¦  «        }t          j        d„ |D ¦   «         t          j        ¬¦  «        }|dk    |dk    z  ||k     z  |dk    z  |dd…df         dk    z  |dd…df         |k     z  |dd…df         dk    z  |dd…df         |k     z  }t          j
        |¦  «        d         }t          |¦  «        dk    r3t          j        ||         ||         g¦  «        |||         ||         f<   t          j        |t          j        ¬¦  «        }|r|r}|j         d         }t          j        |¦  «        }t          dt          |¦  «        dz
  d¦  «        D ]+}||         ||dz            }}||k     r||k     r
|||<   |||<   Œ,|dd…|dd…f         }|S )a  Rebuild transformed keypoints and keep them synchronized with kept boxes.

        Args:
            augmented: Augmented output dict from Albumentations.
            kept_idxs: Original instance indices of surviving boxes.
            keypoints_np: Original keypoint array, shape (N_orig, K, 3).
            flip_pairs: Flat list of paired joint indices ``[a0, b0, a1, b1, ...]``
                to swap when a horizontal flip is detected.  Each consecutive pair
                ``(flip_pairs[i], flip_pairs[i+1])`` names two joints that are
                left/right mirrors of each other (e.g., left_eye, right_eye).
            did_flip: Whether a horizontal flip was applied this step.

        Returns:
            Keypoint tensor of shape ``(len(kept_idxs), K, 3)``.
        r,   rì   r)   c                ó4   — i | ]\  }}t          |¦  «        |“ŒS r9   ©rê   )ry   Úpositionrù   s      r   r‰   zFAlbumentationsWrapper._rebuild_keypoints_from_albu.<locals>.<dictcomp>m  s'   € ÐoÐoÐoÑ@VÀÈ,¥ LÑ 1Ô 1°8ÐoÐoÐor!   r"   Nr°   r+   rÆ   rÇ   rÈ   c                ób   — g | ],}t          |d          ¦  «        t          |d         ¦  «        f‘Œ-S )r   r,   ©rô   ©ry   r‹   s     r   ú
<listcomp>zFAlbumentationsWrapper._rebuild_keypoints_from_albu.<locals>.<listcomp>u  s1   € ÐJÐJÐJ¸A�e A a¤D™kœk­5°°1´©;¬;Ð7ÐJÐJÐJr!   c                óV   •— g | ]%}‰                      t          |¦  «        d ¦  «        ‘Œ&S )r  )r�   rê   )ry   ÚiiÚkept_position_by_idxs     €r   r  zFAlbumentationsWrapper._rebuild_keypoints_from_albu.<locals>.<listcomp>v  s0   ø€ ÐVÐVÐVÀrÐ1×5Ò5µc¸"±g´g¸rÑBÔBÐVÐVÐVr!   c                ó,   — g | ]}t          |¦  «        ‘ŒS r9   r  r  s     r   r  zFAlbumentationsWrapper._rebuild_keypoints_from_albu.<locals>.<listcomp>w  s   € Ð4Ð4Ð4¨�S ™VœVÐ4Ð4Ð4r!   c                ó,   — g | ]}t          |¦  «        ‘ŒS r9   r  )ry   rˆ   s     r   r  zFAlbumentationsWrapper._rebuild_keypoints_from_albu.<locals>.<listcomp>x  s   € Ð8Ð8Ð8¨1�e A™hœhÐ8Ð8Ð8r!   r   )r.   rå   Úzerosr•   r1   rò   r�   Úasarrayræ   ÚintpÚwhereÚcolumn_stackr/   Ú	as_tensorÚarangeÚrange)r  r  rí   r  r  Únum_keypointsÚkeypoints_outr®   r¯   Úalbu_kpsÚinst_idsÚpt_idsrþ   rÅ   ÚinstÚptidÚvisÚvalidÚ	valid_idxÚresultÚnum_kptsÚpermÚiÚaiÚbir  s                            @r   Ú_rebuild_keypoints_from_albuz2AlbumentationsWrapper._rebuild_keypoints_from_albuT  s  ø€ ð. %Ô*¨1Ô-ˆÝœ¥# i¡.¤.°-ÀÐ!CÍ2Ì:ÐVÑVÔVˆØoÐoÕZcÐdmÑZnÔZnÐoÑoÔoÐØ! 'Ô*Ô0°°!°Ô4‰ˆ�à—=’= ¨bÑ1Ô1ˆØñ 	sØ —}’}Ð%<¸bÑAÔAˆHØ—]’]Ð#7¸Ñ<Ô<ˆFØ—m’mÐ$9¸2Ñ>Ô>ˆGÝ”ÐJÐJÀÐJÑJÔJÕRTÔR\Ð]Ñ]Ô]ˆBÝ”8ÐVÐVÐVÐVÈXÐVÑVÔVÕ^`Ô^eÐfÑfÔfˆDÝ”8Ð4Ð4¨VÐ4Ñ4Ô4½B¼GÐDÑDÔDˆDÝ”*Ð8Ð8°Ð8Ñ8Ô8ÅÄ
ÐKÑKÔKˆCà˜’Ø˜1’9ñà˜-Ò'ñ)ð ˜’7ñð �a�a�a˜�d”8˜q’=ñ	"ð
 �a�a�a˜�d”8˜eÒ#ñ%ð �a�a�a˜�d”8˜q’=ñ"ð �a�a�a˜�d”8˜fÒ$ñ&ð õ œ ™œ¨Ô*ˆIÝ�9‰~Œ~ Ò!Ð!ÝBDÄ/ÐSUÐV_ÔS`ÐbeÐfoÔbpÐRqÑBrÔBr�˜d 9œo¨t°I¬Ð>Ñ?å” µe´mÐDÑDÔDˆàð 		(˜
ð 		(à”| A”ˆHÝ”< Ñ)Ô)ˆDÝ˜1�c *™oœo°Ñ1°1Ñ5Ô5ð "ð "�Ø# Aœ¨
°1°q±5Ô(9�B�Ø˜’=�= R¨(¢] ]Ø!�D˜‘HØ!�D˜‘HøØ˜A˜A˜A˜t Q Q Q˜JÔ'ˆFàˆr!   r#   c                ó¦  — ddht           z  }i }|                      ¦   «         D ]­\  }}||v rŒ
t          j        |¦  «        rF|j        dk    r:|j        d         |k    r)|                     dg|j        dd…         ¢R ¦  «        ||<   Œdt          |t          ¦  «        r4t          |t          t          f¦  «        st          |¦  «        |k    rg ||<   Œ®|S )a;  Clear all per-instance fields when no boxes remain.

        >>> import torch
        >>> target = {"area": torch.tensor([100, 200]), "iscrowd": torch.tensor([0, 1])}
        >>> cleared = AlbumentationsWrapper._clear_per_instance_fields(target, 2)
        >>> cleared["area"].shape
        torch.Size([0])
        r(   Úlabelsr,   r   N)r   r˜   r/   râ   Úndimr.   Ú	new_emptyr‘   r   r€   Úbytesr•   )r#   ré   Úglobal_fieldsr2  ÚkeyÚvalues         r   Ú_clear_per_instance_fieldsz0AlbumentationsWrapper._clear_per_instance_fields–  sá   € ð ! (Ð+Õ.GÑGˆà!#ˆØ Ÿ,š,™.œ.ð 	%ð 	%‰JˆC�Ø�mÐ#Ð#ØÝŒ˜uÑ%Ô%ð %Ø”: ’?�? u¤{°1¤~¸Ò'BÐ'BØ"'§/¢/°1Ð2G°u´{À1À2À2´Ð2GÐ2GÑ"HÔ"H�F˜3‘KøÝ˜E¥8Ñ,Ô,ð %µZÀÍÍUÀ|Ñ5TÔ5Tð %Ý�u‘:”: Ò*Ð*Ø"$�F˜3‘KøØˆr!   c                óÄ  ‡— ddht           z  }i }t          j        |t          j        ¬¦  «        }|                      ¦   «         D ]›\  }Š||v rŒ
t          j        ‰¦  «        r(‰j        dk    r‰j        d         |k    r‰|         ||<   ŒFt          ‰t          ¦  «        r@t          ‰t          t          f¦  «        s$t          ‰¦  «        |k    rˆfd„|D ¦   «         ||<   Œœ|S )aN  Filter per-instance fields to match kept box indices.

        >>> import torch
        >>> target = {"area": torch.tensor([100, 200, 300]), "iscrowd": torch.tensor([0, 0, 1])}
        >>> filtered = AlbumentationsWrapper._filter_per_instance_fields(target, 3, [0, 2])
        >>> filtered["area"].tolist()
        [100, 300]
        r(   r:  r)   r,   r   c                ó    •— g | ]
}‰|         ‘ŒS r9   r9   )ry   r5  r@  s     €r   r  zEAlbumentationsWrapper._filter_per_instance_fields.<locals>.<listcomp>Î  s   ø€ Ð"?Ð"?Ð"?° 5¨¤8Ð"?Ð"?Ð"?r!   )r   r/   r%  Úlongr˜   râ   r;  r.   r‘   r   r€   r=  r•   )r#   ré   r  r>  r2  Úkept_idxs_tensorr?  r@  s          @r   Ú_filter_per_instance_fieldsz1AlbumentationsWrapper._filter_per_instance_fields³  s÷   ø€ ð ! (Ð+Õ.GÑGˆà!#ˆÝ œ?¨9½E¼JÐGÑGÔGÐØ Ÿ,š,™.œ.ð 	@ð 	@‰JˆC�Ø�mÐ#Ð#ØÝŒ˜uÑ%Ô%ð @Ø”: ’?�? u¤{°1¤~¸Ò'BÐ'BØ"'Ð(8Ô"9�F˜3‘KøÝ˜E¥8Ñ,Ô,ð @µZÀÍÍUÀ|Ñ5TÔ5Tð @Ý�u‘:”: Ò*Ð*Ø"?Ð"?Ð"?Ð"?°YÐ"?Ñ"?Ô"?�F˜3‘KøØˆr!   Úimage_npúNDArray[np.uint8]r:  ú"tuple[Image.Image, dict[str, Any]]c                ó
  ‡‡‡— |                       |d         ¦  «        }|j        d         }t          t          |¦  «        ¦  «        Šd}d|v r¥|d         }t	          j        |¦  «        r&|                     ¦   «                              ¦   «         nt          j	        |¦  «        }|j
        dk    rt          d|j        › �¦  «        ‚|                     t          j        d¬¦  «        }d	„ |D ¦   «         }d}	d
|v r|                      |d
         |¦  «        }	|dk    r™|dd…df         |dd…df         k    |dd…df         |dd…df         k    z  }
|
                     ¦   «         sPt          j        |
¦  «        d                              ¦   «         }||
         }ˆfd„|D ¦   «         Šˆfd„|D ¦   «         Š||‰‰dœ}|�t%          |¦  «        dk    r||d<   |	�*|                     |                      |	‰¦  «        ¦  «         n|                     g g g g dœ¦  «          | j        d i |¤Ž}|                     ¦   «         }|d         }d„ |                     d‰¦  «        D ¦   «         }t%          |¦  «        dk    r³t	          j        dt          j        ¬¦  «        |d<   t	          j        dt          j        ¬¦  «        |d<   |                     |                      ||¦  «        ¦  «         d|v r>|d         j        dd…         \  }}t	          j        d||ft          j        ¬¦  «        |d<   �n!t	          j        |t          j        ¬¦  «                             dd¦  «        |d<   t	          j        |d         t          j        ¬¦  «        |d<   |                     |                       |||¦  «        ¦  «         d|v r>|d         }|dd…df         |dd…df         z
  |dd…df         |dd…df         z
  z  |d<   |	�S| j!        r(|  "                    |                     d¦  «        ¦  «        nd}|  #                    |||	| j!        |¬¦  «        |d
<   tI          j%        |d         ¦  «        }|�¡d|v r�|d         j        dd…         \  }}|d         Šˆfd„|D ¦   «         Št%          ‰¦  «        dk    r't	          j        d||ft          j        ¬¦  «        |d<   n5t	          j        t          j&        ‰¦  «        t          j        ¬¦  «        |d<   ||fS )!aÇ  Apply geometric transform to image with boxes and optionally masks.

        Converts data to Albumentations format, applies the transform, and converts back to RF-DETR format. Handles box
        removal and per-instance field filtering.

        Args:
            image_np: Numpy array of image in HWC format.
            target: Target dictionary with 'boxes' and optionally 'masks'.
            labels: List of category labels.

        Returns:
            Tuple of (transformed PIL Image, transformed target dict).

        >>> import torch
        >>> from albumentations import HorizontalFlip
        >>> wrapper = AlbumentationsWrapper(HorizontalFlip(p=1.0))
        >>> img = np.ones((100, 100, 3), dtype=np.uint8)
        >>> tgt = {"boxes": torch.tensor([[10, 20, 30, 40]]), "labels": torch.tensor([1])}
        >>> img_out, tgt_out = wrapper._apply_geometric_transform(img, tgt, [1])
        >>> tgt_out["boxes"].shape
        torch.Size([1, 4])
        r(   r   NÚmasksrì   z%masks must have shape (N, H, W), got F)r-   c                ó   — g | ]}|‘ŒS r9   r9   )ry   Úmasks     r   r  zDAlbumentationsWrapper._apply_geometric_transform.<locals>.<listcomp>õ  s   € Ð4Ð4Ð4 4˜$Ð4Ð4Ð4r!   r+   r°   r,   c                ó    •— g | ]
}‰|         ‘ŒS r9   r9   )ry   r5  r:  s     €r   r  zDAlbumentationsWrapper._apply_geometric_transform.<locals>.<listcomp>  s   ø€ Ð=Ð=Ð=¨˜& œ)Ð=Ð=Ð=r!   c                ó    •— g | ]
}‰|         ‘ŒS r9   r9   )ry   r5  rÀ   s     €r   r  zDAlbumentationsWrapper._apply_geometric_transform.<locals>.<listcomp>  s   ø€ Ð9Ð9Ð9 A˜˜QœÐ9Ð9Ð9r!   )r"   Úbboxesr¿   rÀ   rñ   rP  c                ó,   — g | ]}t          |¦  «        ‘ŒS r9   r  )ry   Úidxs     r   r  zDAlbumentationsWrapper._apply_geometric_transform.<locals>.<listcomp>  s   € ÐEÐEÐE #•S˜‘X”XÐEÐEÐEr!   rÀ   )r   rà   r)   )r   r:  r"   r  rà   r¿   Úarear   )r  r  c                ó:   •— g | ]}‰t          |¦  «                 ‘ŒS r9   r  )ry   r5  Ú	masks_augs     €r   r  zDAlbumentationsWrapper._apply_geometric_transform.<locals>.<listcomp><  s$   ø€ Ð>Ð>Ð>¨q˜¥3 q¡6¤6Ô*Ð>Ð>Ð>r!   r9   )'rè   r.   r’   r'  r/   râ   rã   rä   rå   ræ   r;  r“   ÚastypeÚuint8rî   Úallr#  ró   r•   Úupdaterÿ   rr   r-   r�   r   r1   rD  rA  rt   r%  Úreshaper0   rF  rÍ   r  r8  r   Ú	fromarrayÚstack)r   rG  r#   r:  rç   ré   Ú
masks_listrK  Úmasks_nprí   Ú
valid_maskÚvalid_positionsÚtransform_kwargsr  Ú
target_outÚ
bboxes_augr  Ú
aug_heightÚ	aug_widthr(   r  Ú	image_outr®   r¯   rÀ   rU  s      `                    @@r   Ú_apply_geometric_transformz0AlbumentationsWrapper._apply_geometric_transformÑ  sz  øøø€ ð2 ×'Ò'¨¨w¬Ñ8Ô8ˆØ”N 1Ô%ˆ	å•E˜)Ñ$Ô$Ñ%Ô%ˆØˆ
Ø�fÐÐØ˜7”OˆEÝ.3¬o¸eÑ.DÔ.DÐY�u—y’y‘{”{×(Ò(Ñ*Ô*Ð*Í"Ì(ÐSXÉ/Ì/ˆHØŒ} Ò!Ð!Ý Ð!YÈÌÐ!YÐ!YÑZÔZÐZØ—’¥r¤x°e�Ñ<Ô<ˆHØ4Ð4¨8Ð4Ñ4Ô4ˆJØˆØ˜&Ð Ð Ø×3Ò3°F¸;Ô4GÈÑSÔSˆLð
 �qŠ=ˆ=Ø" 1 1 1 a 4œ.¨8°A°A°A°q°D¬>Ò9¸hÀqÀqÀqÈ!Àt¼nÈxÐXYÐXYÐXYÐ[\ÐX\Ì~Ò>]Ñ^ˆJØ—>’>Ñ#Ô#ð :Ý"$¤(¨:Ñ"6Ô"6°qÔ"9×"@Ò"@Ñ"BÔ"B�Ø# JÔ/�Ø=Ð=Ð=Ð=¨_Ð=Ñ=Ô=�ð :Ð9Ð9Ð9¨Ð9Ñ9Ô9�à%-¸ÐSYÐcgÐhÐhÐØÐ!¥c¨*¡o¤o¸Ò&9Ð&9Ø(2Ð˜WÑ%ØÐ#Ø×#Ò# D×$>Ò$>¸|ÈTÑ$RÔ$RÑSÔSÐSÐSà×#Ò#à!#Ø-/Ø*,Ø+-ð	ð ñô ð ð #�D”NÐ6Ð6Ð%5Ð6Ð6ˆ	Ø%+§[¢[¡]¤]ˆ
Ø˜xÔ(ˆ
ØEÐE¨¯ª°v¸tÑ)DÔ)DÐEÑEÔEˆ	åˆz‰?Œ?˜aÒÐÝ"'¤+¨f½E¼MÐ"JÑ"JÔ"JˆJ�wÑÝ#(¤;¨t½5¼:Ð#FÑ#FÔ#FˆJ�xÑ Ø×Ò˜d×=Ò=¸fÀiÑPÔPÑQÔQÐQà˜&Ð Ð Ø(1°'Ô(:Ô(@ÀÀ!ÀÔ(DÑ%�
˜IÝ&+¤k°1°jÀ)Ð2LÕTYÔT^Ð&_Ñ&_Ô&_�
˜7Ñ#ùå"'¤/°*ÅEÄMÐ"RÑ"RÔ"R×"ZÒ"ZÐ[]Ð_`Ñ"aÔ"aˆJ�wÑÝ#(¤<°	¸.Ô0IÕQVÔQ[Ð#\Ñ#\Ô#\ˆJ�xÑ Ø×Ò˜d×>Ò>¸vÀyÐR[Ñ\Ô\Ñ]Ô]Ð]ð ˜Ð#Ð#Ø" 7Ô+�Ø&+¨A¨A¨A¨q¨D¤k°E¸!¸!¸!¸Q¸$´KÑ&?ÀEÈ!È!È!ÈQÈ$ÄKÐRWÐXYÐXYÐXYÐ[\ÐX\ÔR]ÑD]Ñ%^�
˜6Ñ"ØÐ'ð Ô0ð�D×9Ò9¸)¿-º-ÈÑ:QÔ:QÑRÔRÐRàð ð
 +/×*KÒ*KØØØ Ø#Ô8Ø%ð +Lñ +ô +�
˜;Ñ'õ ”O I¨gÔ$6Ñ7Ô7ˆ	ØÐ! g°Ð&:Ð&:Ø% gÔ.Ô4°R°a°RÔ8‰MˆF�EØ! 'Ô*ˆIØ>Ð>Ð>Ð>°IÐ>Ñ>Ô>ˆIÝ�9‰~Œ~ Ò"Ð"Ý&+¤k°1°f¸eÐ2DÍEÌJÐ&WÑ&WÔ&W�
˜7Ñ#Ð#å&+¤oµb´h¸yÑ6IÔ6IÕQVÔQ[Ð&\Ñ&\Ô&\�
˜7Ñ#Ø˜*Ð$Ð$r!   r"   úPIL.Image.Imager$   ú-tuple[PIL.Image.Image, dict[str, Any] | None]c           
     óÜ  — |€kt          j        |¦  «        }| j        r|                      |g g g g g g g ¬¦  «        }n|                      |¬¦  «        }t	          j        |d         ¦  «        dfS t          |t          ¦  «        st          dt          |¦  «        › �¦  «        ‚d|vrt          d¦  «        ‚t          j        |¦  «        }t          j        |d         ¦  «        r,|d                              ¦   «                              ¦   «         nt          |d         ¦  «        }| j        r"d|v rd	|vrt                                d
¦  «         | j        rd	|v r|                      |||¦  «        \  }}nD|                      |¬¦  «        }t	          j        |d         ¦  «        }|                     ¦   «         }d|v r/|j        \  }}	t          j        |	|gt          j        ¬¦  «        |d<   ||fS )a	  Apply the Albumentations transform to image and target.

        This method handles the data format conversion between RF-DETR and Albumentations:
        1. Converts PIL Image to numpy array (required by Albumentations)
        2. Converts PyTorch tensors to numpy/lists (required by Albumentations)
        3. Applies the transform
        4. Converts results back to PIL Image and PyTorch tensors

        For geometric transforms with bounding boxes, this method also:
        - Validates box shapes and coordinates
        - Handles boxes that may be removed by the transform (e.g., cropped out)
        - Ensures labels stay synchronized with their corresponding boxes
        - Transforms masks when present to stay aligned with the image

        Args:
            image: Input PIL Image in RGB format.
            target: Target dictionary containing:
                - 'labels': PyTorch tensor of shape (N,) with class labels
                - 'boxes' (optional): PyTorch tensor of shape (N, 4) in (x1, y1, x2, y2) format
                - 'masks' (optional): PyTorch tensor of shape (N, H, W) with instance segmentation masks.
                  For geometric transforms, masks are transformed alongside boxes to maintain alignment. Requires
                  'boxes' to be present; a warning is logged if masks exist without boxes.
                Pass ``None`` for inference scenarios where no ground-truth annotations are available.

        Returns:
            Tuple of (transformed_image, transformed_target):
                - transformed_image: PIL Image after augmentation
                - transformed_target: Dictionary with augmented boxes and labels, or ``None`` if
                  ``target`` was ``None``.

        Raises:
            TypeError: If target is not a dictionary (and not None).
            KeyError: If target doesn't contain 'labels' key.
            ValueError: If boxes don't have shape (N, 4).

        Examples:
            >>> from albumentations import HorizontalFlip
            >>> wrapper = AlbumentationsWrapper(HorizontalFlip(p=1.0))
            >>> image = Image.new('RGB', (100, 100))
            >>> target = {"boxes": torch.tensor([[10, 20, 90, 80]]), "labels": torch.tensor([1])}
            >>> aug_image, aug_target = wrapper(image, target)
        N)r"   rP  r¿   rÀ   r+   rÆ   rÇ   rÈ   )r"   r"   z!target must be a dictionary, got r:  z target must contain 'labels' keyrK  r(   z¦AlbumentationsWrapper: geometric transform requested with 'masks' but without 'boxes'. Masks will not be geometrically transformed because bounding boxes are missing.r¨   r)   )rå   ræ   rÌ   rr   r   r[  r‘   r”   Ú	TypeErrorr`   ÚKeyErrorr/   râ   rã   ró   r’   rÎ   rÏ   rg  r-   r¨   r%  Úint64)
r   r"   r#   rG  r  r:  rf  rb  r¯   r®   s
             r   r5   zAlbumentationsWrapper.__call__C  s  € ð\ ˆ>Ý”x ‘”ˆHØÔ!ð ;à ŸNšNØ"ØØ!#ØØ Ø*,Ø')Ø(*ð +ñ 	ô 	�	�	ð !ŸNšN°˜NÑ:Ô:�	Ý”? 9¨WÔ#5Ñ6Ô6¸Ð<Ð<õ ˜&¥$Ñ'Ô'ð 	PÝÐNÅÀVÁÄÐNÐNÑOÔOÐOØ˜6Ð!Ð!ÝÐ=Ñ>Ô>Ð>õ ”8˜E‘?”?ˆõ 5:´OÀFÈ8ÔDTÑ4UÔ4UÐq�˜Ô!×%Ò%Ñ'Ô'×.Ò.Ñ0Ô0Ð0Õ[_Ð`fÐgoÔ`pÑ[qÔ[qˆð Ôð 	 '¨VÐ"3Ð"3¸ÀvÐ8MÐ8MÝ�NŠNðbñô ð ð Ôð 	' '¨VÐ"3Ð"3à$(×$CÒ$CÀHÈfÐV\Ñ$]Ô$]Ñ!ˆI�z�zð Ÿš¨X˜Ñ6Ô6ˆIÝœ¨	°'Ô(:Ñ;Ô;ˆIØŸš™œˆJð �ZÐÐà%œN‰MˆE�6Ý!&¤°&¸%°ÍÌÐ!TÑ!TÔ!TˆJ�vÑØ˜*Ð$Ð$r!   Úconfig_dictú%dict[str, Any] | list[dict[str, Any]]Ústrictúlist[AlbumentationsWrapper]c                ó  — t          | t          t          f¦  «        ot          | ¦  «        dk    }t	          | |duo| t
          j        ¬¦  «        } t          | t          ¦  «        r| }nSt          | t          ¦  «        rd„ |                      ¦   «         D ¦   «         }nt          dt          | ¦  «        › �¦  «        ‚|s |sg S t
                               d¦  «         g S t          €t          d¦  «        ‚g }|D �]`}t          |t          ¦  «        rt          |¦  «        dk    rt
                               d	|¦  «         ŒGt          t          |                     ¦   «         ¦  «        ¦  «        \  }}t          |t          ¦  «        r|t          v rd
|i}t          |t          ¦  «        s/t
                               d|t          |¦  «        j        ¦  «         ŒÞ	 t!          ||¦  «        }	|                     t%          |	|¬¦  «        ¦  «         �Œ# t&          $ r@}
|rt)          d|›d|
› �¦  «        |
‚t
                               d|||
¦  «         Y d}
~
�ŒZd}
~
ww xY wt
                               dt          |¦  «        ¦  «         |S )u©  Build a list of :class:`AlbumentationsWrapper` instances from a config.

        Supports both a flat dictionary format (backward-compatible) and a list format that allows duplicate transform
        names and explicit ordering. Container transforms (``OneOf``, ``SomeOf``, ``Sequential``) may be nested
        arbitrarily deep.

        **Dict format** (existing, backward-compatible)::

            config = {
                "HorizontalFlip": {"p": 0.5},
                "Rotate": {"limit": 45, "p": 0.3},
                "OneOf": {
                    "transforms": [
                        {"HorizontalFlip": {"p": 1.0}},
                        {"VerticalFlip": {"p": 1.0}},
                    ],
                },
            }

        **List format** (new; useful when you need two entries with the same name or when explicit order matters)::

            config = [
                {"HorizontalFlip": {"p": 0.5}},
                {"OneOf": {
                    "transforms": [
                        {"Rotate": {"limit": 45, "p": 1.0}},
                        {"ShiftScaleRotate": {"p": 1.0}},
                    ],
                }},
            ]

        **Shorthand for container ``transforms`` list** -- when a container key's value is a *list* rather than a dict,
        it is interpreted as the ``transforms`` parameter::

            {"OneOf": [{"HorizontalFlip": {"p": 1.0}}, {"VerticalFlip": {"p": 1.0}}]}

        Args:
            config_dict: Augmentation configuration -- either a ``dict`` mapping
                transform names to parameter dicts, or a ``list`` of single-key dicts ``{name: params}``.
            keypoint_flip_pairs: Joint index pairs for swapping left/right keypoints after a horizontal
                flip (e.g. ``[0, 1, 2, 3]`` swaps joint 0â†”1 and 2â†”3). Pass ``None`` (default) for
                detection pipelines where horizontal flips are always permitted. Pass an empty list
                ``[]`` to mark a keypoint pipeline without any defined flip pairs -- horizontal-flip
                augmentations are then disabled until flip-pair swapping is implemented.
            strict: When ``True``, a transform that fails to build raises :class:`RuntimeError`
                instead of being logged and skipped. Use for internally-generated pipelines (e.g. the
                required resize stack) where a silently dropped transform would corrupt the output shape.
                Defaults to ``False`` for user augmentation configs, which stay lenient.

        Returns:
            List of :class:`AlbumentationsWrapper` instances in config order.

        Raises:
            ImportError: If Albumentations is not installed.
            TypeError: If *config_dict* is neither a ``dict`` nor a ``list``.
            RuntimeError: If ``strict=True`` and a transform fails to build.

        Examples:
            >>> config = {
            ...     "HorizontalFlip": {"p": 0.5},
            ...     "Rotate": {"limit": 45, "p": 0.3},
            ...     "GaussianBlur": {"p": 0.2}
            ... }
            >>> transforms = AlbumentationsWrapper.from_config(config)  # doctest: +ELLIPSIS
            [...] [INFO] rf-detr - Built 3 Albumentations transforms from config
            >>> [t.transform.transforms[0].__class__.__name__ for t in transforms]
            ['HorizontalFlip', 'Rotate', 'GaussianBlur']

        Note:
            Invalid transforms or invalid parameters are logged and skipped gracefully.
        r   N)Úinclude_keypointsÚwarnc                ó   — g | ]	\  }}||i‘Œ
S r9   r9   r†   s      r   r  z5AlbumentationsWrapper.from_config.<locals>.<listcomp>ü  s    € Ð>Ð>Ð>¡$ ! Q˜˜1�vÐ>Ð>Ð>r!   z.config_dict must be a dictionary or list, got zAEmpty augmentation config provided, no transforms will be appliedr‚   r,   z=Skipping invalid config entry (must be a single-key dict): %rrv   z4Skipping %s: parameters must be a dictionary, got %s)rº   z#Failed to build required transform z: z5Failed to initialize %s with params %r: %s. Skipping.z.Built %d Albumentations transforms from config)r‘   r”   r’   r•   r   rÎ   rÏ   r˜   rk  r`   rp   rŽ   r–   r—   r�   r6   rš   r™   r¹   Ú	ExceptionÚRuntimeErrorÚinfo)rn  rº   rp  Úoriginal_config_emptyÚentriesrv   r¡   Úaug_namerd   rr   Úes              r   Úfrom_configz!AlbumentationsWrapper.from_config¦  sÊ  € õZ !+¨;½½t¸Ñ EÔ EÐ _Í#ÈkÑJZÔJZÐ^_ÒJ_ÐÝ9ØØ1¸Ð=ÐYÐFYÐBYÝ”ð
ñ 
ô 
ˆõ
 �k¥4Ñ(Ô(ð 	bØ!ˆGˆGÝ˜¥TÑ*Ô*ð 	bØ>Ð>¨+×*;Ò*;Ñ*=Ô*=Ð>Ñ>Ô>ˆGˆGåÐ`ÍTÐR]ÑM^ÔM^Ð`Ð`ÑaÔaÐaàð 	Ø(ð Ø�	Ý�NŠNÐ^Ñ_Ô_Ð_ØˆIåˆ;Ýð>ñô ð ð
 ˆ
Øð !	ñ !	ˆEÝ˜e¥TÑ*Ô*ð ­c°%©j¬j¸Aªo¨oÝ—’ØSØñô ð ð Ý#¥D¨¯ª©¬Ñ$7Ô$7Ñ8Ô8ÑˆH�fõ ˜&¥$Ñ'Ô'ð 0¨HÕ8QÐ,QÐ,QØ&¨Ð/�å˜f¥dÑ+Ô+ð Ý—’ØJØÝ˜‘L”LÔ)ñô ð ð
 ðÝ1°(¸FÑCÔC�	Ø×!Ò!Õ"7¸	ÐWjÐ"kÑ"kÔ"kÑlÔlÐlÑløÝð 	ð 	ð 	Øð gÝ&Ð'^ÈXÐ'^Ð'^Ð[\Ð'^Ð'^Ñ_Ô_ÐefÐfÝ—’ØKØØØñ	ô ð ð ���‘øøøøð	øøøõ 	�ŠÐDÅcÈ*ÁoÄoÑVÔVÐVØÐs   Ç4HÈ
IÈ5IÉIr   )rr   rs   rº   r»   r   r   )r   r€   )r(   rÝ   r   rÞ   )r+   rÝ   ré   rê   r   rÞ   )rí   rÞ   rÀ   rï   r   re   )r   r   r   rt   )NF)r  re   r  rï   rí   rÞ   r  r»   r  rt   r   r	   )r#   re   ré   rê   r   re   )r#   re   ré   rê   r  rï   r   re   )rG  rH  r#   re   r:  rï   r   rI  )r"   rh  r#   r$   r   ri  )rn  ro  rº   r»   rp  rt   r   rq  )r6   r7   r8   Ú__doc__r    rÚ   Ústaticmethodrè   rî   rÿ   r  r8  rA  rF  rg  r5   r}  r9   r!   r   r¹   r¹   �  s¥  € € € € € ð(ð (ðT&6ð &6ð &6ð &6ð &6ðPZð Zð Zð Zð* ðð ð ñ „\ðð ðð ð ñ „\ðð" ð
ð 
ð 
ñ „\ð
ð: ðð ð ñ „\ðð< ð
 (,Øð?ð ?ð ?ð ?ñ „\ð?ðB ðð ð ñ „\ðð8 ðð ð ñ „\ðð:p%ð p%ð p%ð p%ðda%ð a%ð a%ð a%ðF ð 15ØðJð Jð Jð Jñ „\ðJð Jð Jr!   r¹   )r   r`   )rr   rs   r   rt   )r   r€   rd   re   r   rs   )r¦   r`   r   rt   )r   r€   rd   re   r¦   r`   r   re   )-r~  Ú
__future__r   r©   Úcollections.abcr   Ú	functoolsr   Útypingr   Úalbumentationsrp   rŽ   rä   rå   ÚPILr/   Únumpy.typingr   r   r	   Útorchvision.transformsr
   r   Úrfdetr.datasets._aug_utilsr   r   r   r   r   Úrfdetr.utilities.box_opsr   Úrfdetr.utilities.loggerr   rÎ   r|   Ú	frozensetr�   r�   rq   rx   rš   r¬   rž   r¹   r9   r!   r   ú<module>rŒ     s¢  ðð >Ð =à "Ð "Ð "Ð "Ð "Ð "à €€€Ø $Ð $Ð $Ð $Ð $Ð $Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð ðØ Ð Ð Ð Ð øØð ð ð Ø
€C€C€Cðøøøà Ð Ð Ð Ø 
€
€
€
Ø €€€Ø  Ð  Ð  Ð  Ð  Ð  Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø <Ð <Ð <Ð <Ð <Ð <ðð ð ð ð ð ð ð ð ð ð ð ð ð ð 8Ð 7Ð 7Ð 7Ð 7Ð 7Ø .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€ð3ð 3ð 3ð 3ð 3ñ 3ô 3ð 3ðv*ð *ð *ðT ñU*Ð ðZ &˜IÐ&GÐ&GÐ&GÑHÔHÐ ð !7Ð ð ð ð  ð  ñ „ð ð6ð ð ð ð:MDð MDð MDð MDð` ð*ð *ð *ñ „ð*ð"Rð Rð Rð Rðjb
ð b
ð b
ð b
ð b
ñ b
ô b
ð b
ð b
ð b
s    % ¥/®/