§
    ­¸j›c  ã                  ó  — U d Z ddlmZ ddlmZ ddlmZmZ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 dd	lmZ dd
lmZ  edh¦  «        ez  Zej        ej        z  Zded<   eeeef                  Zded<   e	eef         Zded<   d9d„Zd:d„Z d;d„Z!d<d„Z"d=d$„Z#d>d%„Z$ G d&„ d'¦  «        Z% G d(„ d)¦  «        Z& G d*„ d+¦  «        Z' G d,„ d-¦  «        Z( G d.„ d/¦  «        Z) G d0„ d1¦  «        Z* G d2„ d3¦  «        Z+d?d8„Z,dS )@aJ  Torchvision-native image/target transforms for RF-DETR dataset pipelines.

Provides drop-in replacements for Albumentations-based augmentations using
``torchvision.transforms.v2`` primitives. All transforms accept ``(image, target)``
pairs where ``image`` is a PIL image or ``torch.Tensor`` and ``target`` is an
optional dict with keys ``boxes``, ``labels``, ``masks``, ``keypoints``, etc.

Examples:
    >>> from rfdetr.datasets._torchvision import Compose, Resize
    >>> from rfdetr.datasets.transforms import Normalize
    >>> transform = Compose([Resize((640, 640)), Normalize()])
é    )Úannotations)ÚSequence)ÚAnyÚDictÚOptionalÚTupleÚ	TypeAliasÚcastN)ÚImage)Ú
tv_tensors)ÚInterpolationMode)Ú
functional)ÚIMAGE_LEVEL_TARGET_FIELDSÚboxesr	   Ú_ImageInputÚ_TargetÚ_TransformResultÚimageúImage.Image | torch.TensorÚreturnútuple[int, int]c                óº   — t          | t          j        ¦  «        r| j        \  }}||fS t          | j        d         ¦  «        t          | j        d         ¦  «        fS )z‘Return image size as ``(height, width)``.

    Args:
        image: PIL image or tensor image.

    Returns:
        Image height and width.
    éþÿÿÿéÿÿÿÿ)Ú
isinstancer   ÚsizeÚintÚshape)r   ÚwidthÚheights      úl/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/datasets/_torchvision.pyÚ_image_sizer"   ,   sT   € õ �%�œÑ%Ô%ð Øœ
‰ˆˆvØ�uˆ}ÐÝˆuŒ{˜2ŒÑÔ¥ U¤[°¤_Ñ!5Ô!5Ð5Ð5ó    útorch.TensorÚ	canvas_hwÚopr   c                óò   — t          j        |                      ¦   «         t           j        j        |¬¦  «        }t          t          j         ||¦  «                             t          j        ¦  «        ¦  «        S )aª  Apply a torchvision geometric functional op to absolute xyxy boxes.

    Wraps ``boxes`` as ``tv_tensors.BoundingBoxes`` so ``op`` (a ``torchvision.transforms.v2``
    functional such as ``resize``/``horizontal_flip``/``crop``) updates coordinates using
    torchvision's own tested geometry math instead of hand-rolled arithmetic.

    Args:
        boxes: Absolute xyxy box tensor of shape ``(N, 4)``, any numeric dtype.
        canvas_hw: Current image ``(height, width)`` the boxes are defined against.
        op: Callable taking a ``tv_tensors.BoundingBoxes`` and returning one.

    Returns:
        Plain ``float32`` tensor of shape ``(N, 4)`` with updated coordinates.
    )ÚformatÚcanvas_size)	r   ÚBoundingBoxesÚfloatÚBoundingBoxFormatÚXYXYr
   ÚtorchÚTensorÚas_subclass)r   r%   r&   Úwrappeds       r!   Ú_apply_to_boxesr2   ;   sT   € õ Ô& u§{¢{¡}¤}½ZÔ=YÔ=^ÐluÐvÑvÔv€GÝ•”˜b˜b ™kœk×5Ò5µe´lÑCÔCÑDÔDÐDr#   Úmasksc                óÂ   — t          j        | t          j        ¬¦  «        }t	          t          j         ||¦  «                             t          j        ¦  «        ¦  «        S )ag  Apply a torchvision geometric functional op to boolean instance masks.

    Wraps ``masks`` as ``tv_tensors.Mask`` so ``op`` resizes/crops/flips with torchvision's
    nearest-neighbor mask handling, verified bitwise-equal to the previous manual
    ``interpolate(..., mode="nearest")`` implementation. Unlike boxes, masks carry their own
    spatial size, so no separate ``canvas_hw`` is needed.

    Args:
        masks: Boolean mask tensor of shape ``(N, H, W)``.
        op: Callable taking a ``tv_tensors.Mask`` and returning one.

    Returns:
        Boolean mask tensor with updated spatial dimensions.
    )Údtype)r   ÚMaskr.   Úboolr
   r/   r0   )r3   r&   r1   s      r!   Ú_apply_to_masksr8   N   sD   € õ Œo˜e­5¬:Ð6Ñ6Ô6€GÝ•”˜b˜b ™kœk×5Ò5µe´lÑCÔCÑDÔDÐDr#   ÚtargetúDict[str, Any]Úkeepc                ó¨  ‡— |                       ¦   «         }t          | d         j        d         ¦  «        }|                     d¬¦  «                             ¦   «         }||d<   |                      ¦   «         D ] \  }Š|t          v rŒt          j        ‰¦  «        r(‰j	        dk    r‰j        d         |k    r‰|         ||<   ŒKt          ‰t          ¦  «        r@t          ‰t          t          f¦  «        s$t          ‰¦  «        |k    rˆfd„|D ¦   «         ||<   Œ¡d|v r6|dd…d	f         |dd…df         z
  |dd…d
f         |dd…df         z
  z  |d<   |S )a9  Filter target fields whose first dimension matches the number of boxes.

    Args:
        target: Target dictionary before filtering.
        keep: Boolean tensor indicating surviving box rows.
        boxes: Already-filtered boxes.

    Returns:
        Target dictionary with per-instance fields filtered.
    r   r   F)Úas_tupleé   c                ó:   •— g | ]}‰t          |¦  «                 ‘ŒS © ©r   )Ú.0ÚiÚvalues     €r!   ú
<listcomp>z/_filter_per_instance_fields.<locals>.<listcomp>v   s#   ø€ Ð?Ð?Ð?°˜u¥S¨¡V¤Vœ}Ð?Ð?Ð?r#   ÚareaNé   é   )Úcopyr   r   ÚnonzeroÚflattenÚitemsÚ_GLOBAL_TARGET_FIELDSr.   Ú	is_tensorÚndimr   r   ÚstrÚbytesÚlen)r9   r;   r   Ú
target_outÚ	num_boxesÚkeep_idxÚkeyrD   s          @r!   Ú_filter_per_instance_fieldsrW   a   sw  ø€ ð "(§¢¡¤€JÝ�F˜7”OÔ)¨!Ô,Ñ-Ô-€IØ�|Š| Uˆ|Ñ+Ô+×3Ò3Ñ5Ô5€HØ€JˆwÑØ—l’l‘n”nð @ð @‰
ˆˆUØÕ'Ð'Ð'ØÝŒ?˜5Ñ!Ô!ð 	@ e¤j°A¢o o¸%¼+Àa¼.ÈIÒ:UÐ:UØ# HœoˆJ�s‰OˆOÝ˜�xÑ(Ô(ð 	@µ¸EÅCÍÀ<Ñ1PÔ1Pð 	@ÕUXÐY^ÑU_ÔU_ÐclÒUlÐUlØ?Ð?Ð?Ð?°hÐ?Ñ?Ô?ˆJ�s‰Oøà�ÐÐØ# A A A q Dœk¨E°!°!°!°Q°$¬KÑ7¸EÀ!À!À!ÀQÀ$¼KÈ%ÐPQÐPQÐPQÐSTÐPTÌ+Ñ<UÑVˆ
�6ÑØÐr#   Ú	keypointsr    r   r   c                ó"  — |                       ¦   «         dk    r| S | d         dk    }| d         dk    | d         |k     z  | d         dk    z  | d         |k     z  }||z   }|                     ¦   «         s| S |                      ¦   «         } d| |<   | S )zìClear keypoints that are invisible or outside the image.

    Args:
        keypoints: Keypoint tensor of shape ``(N, K, 3)``.
        height: Image height.
        width: Image width.

    Returns:
        Updated keypoint tensor.
    r   ©.rG   ©.r   ©.r>   ç        )ÚnumelÚanyÚclone)rX   r    r   ÚvisibleÚinsideÚinvalids         r!   Ú_mark_invisible_keypointsrd   }   sµ   € ð ‡‚ÑÔ˜AÒÐØÐØ˜Ô !Ò#€Gà	�6Ô	˜aÒ	 I¨fÔ$5¸Ò$=Ñ>À)ÈFÔBSÐWXÒBXÑYÐ]fÐgmÔ]nÐqwÒ]wÑxð ð ˜&Ñ Ð!€GØ�;Š;‰=Œ=ð ØÐØ—’Ñ!Ô!€IØ€IˆgÑØÐr#   c                ó”   — |                       ¦   «         }t          j        t          |¦  «        t          |¦  «        g¦  «        |d<   |S )zñUpdate the current image size in a target dictionary.

    Args:
        target: Target dictionary.
        height: Current image height.
        width: Current image width.

    Returns:
        Target dictionary with updated ``size``.
    r   )rI   r.   Ú	as_tensorr   )r9   r    r   rS   s       r!   Ú_update_sizerg   –   s<   € ð —’‘”€JÝœ­#¨f©+¬+µs¸5±z´zÐ)BÑCÔC€JˆvÑØÐr#   c                  ó(   — e Zd ZdZddd
„Z	 ddd„ZdS )ÚRandomSelectu  Select one of two image/target transforms with probability ``p``.

    Note:
        Not a torchvision transform: ``T.RandomApply`` applies one transform or the identity
        with probability ``p``, and ``T.RandomChoice`` picks uniformly (or by weighted ``p``
        list) among N transforms â€” neither expresses "always apply exactly one of two, chosen
        by a single coin flip", which is the original DETR augmentation combinator this mirrors.

    Args:
        transform1: Transform used when the sampled value is below ``p``.
        transform2: Transform used otherwise.
        p: Probability of selecting ``transform1``.

    Examples:
        >>> t1 = Resize((480, 480))
        >>> t2 = Resize((640, 640))
        >>> selector = RandomSelect(t1, t2, p=0.5)
    ç      à?Ú
transform1r   Ú
transform2Úpr+   r   ÚNonec                ó0   — || _         || _        || _        d S ©N)rk   rl   rm   )Úselfrk   rl   rm   s       r!   Ú__init__zRandomSelect.__init__º   s   € Ø$ˆŒØ$ˆŒØˆŒˆˆr#   Nr   r   r9   úOptional[Dict[str, Any]]ú;Tuple[Image.Image | torch.Tensor, Optional[Dict[str, Any]]]c                óà   — t          j        d¦  «        | j        k     r)t          t          |                      ||¦  «        ¦  «        S t          t          |                      ||¦  «        ¦  «        S )zËApply one of the configured transforms.

        Args:
            image: Input image.
            target: Optional target dictionary.

        Returns:
            Transformed image and target.
        r@   )r.   Úrandrm   r
   r   rk   rl   )rq   r   r9   s      r!   Ú__call__zRandomSelect.__call__¿   sW   € õ Œ:�b‰>Œ>˜DœFÒ"Ð"ÝÕ(¨$¯/ª/¸%ÀÑ*HÔ*HÑIÔIÐIÝÕ$ d§o¢o°e¸VÑ&DÔ&DÑEÔEÐEr#   )rj   )rk   r   rl   r   rm   r+   r   rn   rp   ©r   r   r9   rs   r   rt   ©Ú__name__Ú
__module__Ú__qualname__Ú__doc__rr   rw   r@   r#   r!   ri   ri   ¦   s^   € € € € € ðð ð&ð ð ð ð ð UYðFð Fð Fð Fð Fð Fð Fr#   ri   c                  ó&   — e Zd ZdZdd„Z	 ddd„ZdS )ÚRandomChoicea¹  Select one transform uniformly from a sequence.

    Note:
        ``torchvision.transforms.v2.RandomChoice`` does the same sampling but calls each
        candidate as ``transform(*inputs)`` under torchvision's flexible-tree calling
        convention. This module's transforms use an explicit ``(image, target)`` two-argument
        signature (``target`` may be ``None``), so a thin reimplementation is needed to dispatch
        correctly rather than adapting every transform to torchvision's convention.

    Args:
        transforms: Candidate transforms.

    Examples:
        >>> t1 = Resize((480, 480))
        >>> t2 = Resize((640, 640))
        >>> choice = RandomChoice([t1, t2])
    Ú
transformsúSequence[Any]r   rn   c                óP   — |st          d¦  «        ‚t          |¦  «        | _        d S )Nz.transforms must contain at least one transform)Ú
ValueErrorÚlistr€   ©rq   r€   s     r!   rr   zRandomChoice.__init__ã   s-   € Øð 	OÝÐMÑNÔNÐNÝ˜zÑ*Ô*ˆŒˆˆr#   Nr   r   r9   rs   rt   c                ó  — t          | j        ¦  «        dk    rFt          t          j        t          | j        ¦  «        d¦  «                             ¦   «         ¦  «        nd}t          t           | j        |         ||¦  «        ¦  «        S )zÊApply one randomly selected transform.

        Args:
            image: Input image.
            target: Optional target dictionary.

        Returns:
            Transformed image and target.
        r>   r@   r   )rR   r€   r   r.   ÚrandintÚitemr
   r   )rq   r   r9   Úindexs       r!   rw   zRandomChoice.__call__è   su   € õ HKÈ4Ì?ÑG[ÔG[Ð^_ÒG_ÐG_••E”M¥# d¤oÑ"6Ô"6¸Ñ;Ô;×@Ò@ÑBÔBÑCÔCÐCÐefˆÝÕ$Ð&< d¤o°eÔ&<¸UÀFÑ&KÔ&KÑLÔLÐLr#   ©r€   r�   r   rn   rp   rx   ry   r@   r#   r!   r   r   Ð   sY   € € € € € ðð ð$+ð +ð +ð +ð UYðMð Mð Mð Mð Mð Mð Mr#   r   c                  ó&   — e Zd ZdZdd„Z	 ddd„ZdS )ÚComposeaØ  Compose RF-DETR image/target transforms.

    Note:
        ``torchvision.transforms.v2.Compose`` chains transforms called as ``transform(*inputs)``
        over an arbitrary input tree. This module's transforms use the explicit two-argument
        ``(image, target)`` signature instead (with ``target`` threaded through and possibly
        ``None``), so the chaining loop is reimplemented to match that signature rather than
        torchvision's.

    Args:
        transforms: Sequence of transforms accepting ``(image, target)``.

    Examples:
        >>> from rfdetr.datasets._torchvision import Compose, Resize, RandomHorizontalFlip
        >>> pipeline = Compose([Resize((640, 640)), RandomHorizontalFlip(p=0.5)])
    r€   r�   r   rn   c                ó.   — t          |¦  «        | _        d S rp   )r„   r€   r…   s     r!   rr   zCompose.__init__
  s   € Ý˜zÑ*Ô*ˆŒˆˆr#   Nr   r   r9   rs   rt   c                ó<   — | j         D ]} |||¦  «        \  }}Œ||fS )z¾Apply transforms in order.

        Args:
            image: Input image.
            target: Optional target dictionary.

        Returns:
            Transformed image and target.
        )r€   )rq   r   r9   Ú	transforms       r!   rw   zCompose.__call__  s6   € ð œð 	5ð 	5ˆIØ%˜I e¨VÑ4Ô4‰MˆE�6�6Ø�fˆ}Ðr#   rŠ   rp   rx   ry   r@   r#   r!   rŒ   rŒ   ø   sR   € € € € € ðð ð"+ð +ð +ð +ð UYðð ð ð ð ð ð r#   rŒ   c                  ó@   — e Zd ZdZddd	„Z	 ddd„Zedd„¦   «         ZdS )ÚRandomResizeuh  Resize so the shortest side matches a sampled size, with an optional long-side cap.

    Note:
        ``torchvision.transforms.v2.RandomShortestSize(min_size, max_size)`` performs this same
        sample-then-cap sizing. It isn't used directly because it only resizes an image (or a
        single tv_tensor); it has no notion of the ``(image, target)`` dict pipeline used here
        (keypoint scaling, ``area`` recompute, ``size``/``orig_size`` bookkeeping), so delegating
        to it would still require the same dict-aware wrapper this class already provides via
        :class:`Resize` â€” no simplification to gain, only churn on an already-tested path.

    Args:
        sizes: Candidate shortest-side sizes.
        max_size: Optional maximum longest side after resizing.

    Examples:
        >>> resizer = RandomResize([480, 512, 640], max_size=1333)
    NÚsizesúSequence[int]Úmax_sizeú
int | Noner   rn   c                óX   — |st          d¦  «        ‚d„ |D ¦   «         | _        || _        d S )Nz%sizes must contain at least one valuec                ó,   — g | ]}t          |¦  «        ‘ŒS r@   rA   )rB   r   s     r!   rE   z)RandomResize.__init__.<locals>.<listcomp>4  s   € Ð2Ð2Ð2 D•c˜$‘i”iÐ2Ð2Ð2r#   )rƒ   r’   r”   )rq   r’   r”   s      r!   rr   zRandomResize.__init__1  s:   € Øð 	FÝÐDÑEÔEÐEØ2Ð2¨EÐ2Ñ2Ô2ˆŒ
Ø ˆŒˆˆr#   r   r   r9   rs   rt   c                óv  — t          | j        ¦  «        dk    rFt          t          j        t          | j        ¦  «        d¦  «                             ¦   «         ¦  «        nd}| j        |         }t          |¦  «        \  }}|                      |||| j        ¦  «        \  }} t          ||f¦  «        ||¦  «        S )úËResize the image and spatial target fields.

        Args:
            image: Input image.
            target: Optional target dictionary.

        Returns:
            Resized image and target.
        r>   r@   r   )
rR   r’   r   r.   r‡   rˆ   r"   Ú	_get_sizer”   ÚResize)	rq   r   r9   r‰   r   r    r   Ú
new_heightÚ	new_widths	            r!   rw   zRandomResize.__call__7  s¦   € õ CFÀdÄjÁ/Ä/ÐTUÒBUÐBU••E”M¥# d¤j¡/¤/°2Ñ6Ô6×;Ò;Ñ=Ô=Ñ>Ô>Ð>Ð[\ˆØŒz˜%Ô ˆÝ# EÑ*Ô*‰ˆ�Ø $§¢¨v°u¸dÀDÄMÑ RÔ RÑˆ
�IØ.�v�z 9Ð-Ñ.Ô.¨u°fÑ=Ô=Ð=r#   r    r   r   r   r   c                ó´  — t          t          | |¦  «        ¦  «        }t          t          | |¦  «        ¦  «        }|�.||z  |z  |k    r"t          t	          ||z  |z  ¦  «        ¦  «        }|| k    r||k    s| |k    r
| |k    r| |fS || k     r%|}t          t	          || z  |z  ¦  «        ¦  «        }n$|}t          t	          ||z  | z  ¦  «        ¦  «        }||fS )a   Compute output size preserving aspect ratio.

        Args:
            height: Input height.
            width: Input width.
            size: Requested shortest side.
            max_size: Optional maximum longest side.

        Returns:
            Output ``(height, width)``.
        )r+   ÚminÚmaxr   Úround)r    r   r   r”   Úmin_originalÚmax_originalr�   rœ   s           r!   rš   zRandomResize._get_sizeI  só   € õ �S ¨Ñ/Ô/Ñ0Ô0ˆÝ�S ¨Ñ/Ô/Ñ0Ô0ˆØÐ L°<Ñ$?À$Ñ$FÈÒ$QÐ$QÝ•u˜X¨Ñ4°|ÑCÑDÔDÑEÔEˆDà�VŠOˆO ¨¢ °6¸U²?°?ÀvÐQUÂ~À~Ø˜5�=Ð à�6Š>ˆ>ØˆIÝ�U 4¨&¡=°5Ñ#8Ñ9Ô9Ñ:Ô:ˆJˆJàˆJÝ�E $¨¡,°Ñ"7Ñ8Ô8Ñ9Ô9ˆIØ˜9Ð$Ð$r#   rp   )r’   r“   r”   r•   r   rn   rx   )
r    r   r   r   r   r   r”   r•   r   r   )rz   r{   r|   r}   rr   rw   Ústaticmethodrš   r@   r#   r!   r‘   r‘     sw   € € € € € ðð ð$!ð !ð !ð !ð !ð UYð>ð >ð >ð >ð >ð$ ð%ð %ð %ñ „\ð%ð %ð %r#   r‘   c                  ó&   — e Zd ZdZdd„Z	 ddd„ZdS )r›   up  Resize to a fixed ``(height, width)``.

    Note:
        ``torchvision.transforms.v2.Resize`` resizes an image (or, given tv_tensors, boxes/masks/
        keypoints alongside it) but has no concept of this project's ``target`` dict â€” it doesn't
        know about ``keypoints`` visibility semantics (no visibility channel in
        ``tv_tensors.KeyPoints``), ``area`` recompute, or ``size``/``orig_size`` bookkeeping. This
        class is a dict-aware wrapper that coordinates the image resize with box/mask geometry
        (delegated to ``tv_tensors`` + native ``functional.resize`` via :func:`_apply_to_boxes` /
        :func:`_apply_to_masks`) and manual keypoint/area/size updates â€” it composes torchvision's
        resize rather than reimplementing it.

    Args:
        size: Output ``(height, width)``.

    Examples:
        >>> resizer = Resize((640, 640))
    r   r   r   rn   c                ód   — t          |d         ¦  «        t          |d         ¦  «        f| _        d S ©Nr   r>   )r   r   )rq   r   s     r!   rr   zResize.__init__{  s&   € Ý˜˜aœ‘\”\¥3 t¨A¤w¡<¤<Ð0ˆŒ	ˆ	ˆ	r#   Nr   r   r9   rs   rt   c                ól  ‡	‡
— t          |¦  «        \  }}| j        \  Š	Š
t          j        |‰	‰
gt          j        d¬¦  «        }|€|dfS |                     ¦   «         }‰
|z  }‰	|z  }d|v r t          |d         ||fˆ	ˆ
fd„¦  «        |d<   d|v rt          |d         ˆ	ˆ
fd„¦  «        |d<   d|v r^|d          	                    ¦   «          
                    ¦   «         }|d	         |z  |d	<   |d
         |z  |d
<   t          |‰	‰
¦  «        }||d<   d|v r|d         ||z  z  |d<   |t          |‰	‰
¦  «        fS )r™   T)ÚinterpolationÚ	antialiasNr   c                ó2   •— t          j        | ‰‰g¦  «        S rp   ©r   Úresize)r   rœ   r�   s    €€r!   ú<lambda>z!Resize.__call__.<locals>.<lambda>¢  s   ø€ �jÔ/°¸
ÀIÐ7NÑOÔO€ r#   r3   c                ó2   •— t          j        | ‰‰g¦  «        S rp   r¬   )r3   rœ   r�   s    €€r!   r®   z!Resize.__call__.<locals>.<lambda>¦  s   ø€ µ:Ô3DÀUÈZÐYbÐLcÑ3dÔ3d€ r#   rX   r[   r\   rF   )r"   r   r   r­   r   ÚBILINEARrI   r2   r8   r+   r`   rd   rg   )rq   r   r9   Ú
old_heightÚ	old_widthrS   Úratio_widthÚratio_heightrX   rœ   r�   s            @@r!   rw   zResize.__call__~  s¦  øø€ õ !,¨EÑ 2Ô 2Ñˆ
�IØ $¤	Ñˆ
�Iõ Ô!ØØ˜Ð#Ý+Ô4Øð	
ñ 
ô 
ˆð ˆ>Ø˜$�;Ðà—[’[‘]”]ˆ
Ø )Ñ+ˆØ! JÑ.ˆØ�jÐ Ð Ý"1Ø˜7Ô#Ø˜YÐ'ØOÐOÐOÐOÐOñ#ô #ˆJ�wÑð
 �jÐ Ð Ý"1Ø˜7Ô#Ð%dÐ%dÐ%dÐ%dÐ%dñ#ô #ˆJ�wÑð ˜*Ð$Ð$Ø" ;Ô/×5Ò5Ñ7Ô7×=Ò=Ñ?Ô?ˆIØ )¨&Ô 1°KÑ ?ˆI�fÑØ )¨&Ô 1°LÑ @ˆI�fÑÝ1°)¸ZÈÑSÔSˆIØ&/ˆJ�{Ñ#Ø�ZÐÐØ!+¨FÔ!3°{À\Ñ7QÑ!RˆJ�vÑØ•l :¨z¸9ÑEÔEÐEÐEr#   )r   r   r   rn   rp   rx   ry   r@   r#   r!   r›   r›   g  sY   € € € € € ðð ð&1ð 1ð 1ð 1ð UYð2Fð 2Fð 2Fð 2Fð 2Fð 2Fð 2Fr#   r›   c                  ó&   — e Zd ZdZdd„Z	 ddd„ZdS )ÚRandomSizedCropu@  Crop a random square-ish region and resize it to a fixed output size.

    Note:
        Not a reimplementation of an existing torchvision transform. The closest analog,
        ``T.RandomResizedCrop``, samples crop geometry via an area-*scale* range and an
        aspect-*ratio* range (Inception-style). This class instead samples a single square-ish
        crop side length uniformly from a pixel range and crops at a random position â€” the
        DETR/Deformable-DETR "resize-and-crop" augmentation policy, a distinct sampling strategy
        rather than a different implementation of the same one.

    Args:
        min_max_height: Inclusive candidate range for the crop height.
        size: Output ``(height, width)`` after crop resizing.

    Examples:
        >>> cropper = RandomSizedCrop((384, 600), (640, 640))
    Úmin_max_heightr   r   r   rn   c                óÂ   — t          |d         ¦  «        t          |d         ¦  «        f| _        t          |d         ¦  «        t          |d         ¦  «        f| _        d S r§   )r   r·   r   )rq   r·   r   s      r!   rr   zRandomSizedCrop.__init__Æ  sM   € Ý" >°!Ô#4Ñ5Ô5µs¸>È!Ô;LÑ7MÔ7MÐNˆÔÝ˜˜aœ‘\”\¥3 t¨A¤w¡<¤<Ð0ˆŒ	ˆ	ˆ	r#   Nr   r   r9   rs   rt   c                ó²  — t          |¦  «        \  }}| j        \  }}t          |||¦  «        }t          ||¦  «        }||k    r8t          t	          j        ||dz   d¦  «                             ¦   «         ¦  «        n|}t          ||¦  «        }t          ||¦  «        }	||k    r;t          t	          j        d||z
  dz   d¦  «                             ¦   «         ¦  «        nd}
||	k    r;t          t	          j        d||	z
  dz   d¦  «                             ¦   «         ¦  «        nd}t          |||
|||	¦  «        \  }} t          | j	        ¦  «        ||¦  «        S )zàCrop and resize the image and spatial target fields.

        Args:
            image: Input image.
            target: Optional target dictionary.

        Returns:
            Cropped and resized image and target.
        r>   r@   r   )
r"   r·   rŸ   r   r.   r‡   rˆ   Úcropr›   r   )rq   r   r9   r    r   Úmin_cropÚmax_cropÚ	crop_sizeÚcrop_heightÚ
crop_widthÚtopÚlefts               r!   rw   zRandomSizedCrop.__call__Ê  sW  € õ $ EÑ*Ô*‰ˆ�Ø!Ô0Ñˆ�(Ý�x ¨Ñ/Ô/ˆÝ�x Ñ*Ô*ˆØMUÐX`ÒM`ÐM`•C�œ h°¸1±¸bÑAÔA×FÒFÑHÔHÑIÔIÐIÐfnˆ	Ý˜) VÑ,Ô,ˆÝ˜ EÑ*Ô*ˆ
ØLRÐU`ÒL`ÐL`�c•%”-  6¨KÑ#7¸!Ñ#;¸RÑ@Ô@×EÒEÑGÔGÑHÔHÐHÐfgˆØKPÐS]ÒK]ÐK]�s•5”=  E¨JÑ$6¸Ñ$:¸BÑ?Ô?×DÒDÑFÔFÑGÔGÐGÐcdˆÝ˜U F¨C°°{ÀJÑOÔO‰ˆˆvØ �v�d”iÑ Ô  ¨Ñ/Ô/Ð/r#   )r·   r   r   r   r   rn   rp   rx   ry   r@   r#   r!   r¶   r¶   ³  sR   € € € € € ðð ð$1ð 1ð 1ð 1ð
 UYð0ð 0ð 0ð 0ð 0ð 0ð 0r#   r¶   c                  ó(   — e Zd ZdZddd
„Z	 ddd„ZdS )ÚRandomHorizontalFlipuÝ  Horizontally flip an image/target pair with probability ``p``.

    Note:
        ``torchvision.transforms.v2.RandomHorizontalFlip`` flips an image (or tv_tensors passed
        alongside it) but has no ``target`` dict awareness: it can't apply ``keypoint_flip_pairs``
        (swapping e.g. left/right joint indices, a pose-estimation concept torchvision doesn't
        model) and ``tv_tensors.KeyPoints`` has no visibility channel to mask on flip. This class
        wraps native ``functional.horizontal_flip`` for the image/box/mask geometry (box flip via
        :func:`_apply_to_boxes`) and adds the manual keypoint mirror + visibility handling +
        flip-pair swap on top.

    Args:
        p: Flip probability.
        keypoint_flip_pairs: Flat even-length list of index pairs ``(left_i, right_i, ...)`` to swap on horizontal flip.
            For example, ``[0, 1, 4, 5]`` swaps keypoints 0â†”1 and 4â†”5.

    Examples:
        >>> flipper = RandomHorizontalFlip(p=0.5)
    rj   Nrm   r+   Úkeypoint_flip_pairsúSequence[int] | Noner   rn   c                ó¾   — || _         t          |pg ¦  «        | _        t          | j        ¦  «        dz  dk    r$t	          dt          | j        ¦  «        › �¦  «        ‚d S )NrG   r   z>keypoint_flip_pairs must have an even number of elements, got )rm   r„   rÄ   rR   rƒ   )rq   rm   rÄ   s      r!   rr   zRandomHorizontalFlip.__init__ø  sl   € ØˆŒÝ#'Ð(;Ð(A¸rÑ#BÔ#BˆÔ ÝˆtÔ'Ñ(Ô(¨1Ñ,°Ò1Ð1ÝØpÕQTÐUYÔUmÑQnÔQnÐpÐpñô ð ð 2Ð1r#   r   r   r9   rs   rt   c                óÞ  — t          j        d¦  «        | j        k    r||fS t          |¦  «        \  }}t	          j        |¦  «        }|€|dfS |                     ¦   «         }d|v r&t          |d         ||ft          j        ¦  «        |d<   d|v rt	          j        |d         ¦  «        |d<   d|v �r9|d                              ¦   «         }|d         dk    }|dz
  |d	         z
  |d	<   |  	                    d
¦  «        }|ddd…f          
                    |d¦  «        |ddd…f<   | j        rª| j        }	t          t          |j        d         ¦  «        ¦  «        }
t          dt          |	¦  «        d¦  «        D ]N}|	|         |	|dz            }}||j        d         k     r(||j        d         k     r|
|         |
|         c|
|<   |
|<   ŒO|dd…|
dd…f         }t!          |||¦  «        |d<   ||fS )zÌRandomly flip the image and target.

        Args:
            image: Input image.
            target: Optional target dictionary.

        Returns:
            Possibly flipped image and target.
        r@   Nr   r3   rX   rZ   r   r>   r[   r   .rG   r]   )r.   rv   rm   r"   r   Úhorizontal_fliprI   r2   r`   Ú	unsqueezeÚmasked_fillrÄ   r„   Úranger   rR   rd   )rq   r   r9   r    r   rS   rX   ra   Ú	invisibleÚpairsÚpermrC   ÚaiÚbis                 r!   rw   zRandomHorizontalFlip.__call__   s!  € õ Œ:�b‰>Œ>˜TœVÒ#Ð#Ø˜&�=Ð å# EÑ*Ô*‰ˆ�ÝÔ*¨5Ñ1Ô1ˆØˆ>Ø˜$�;Ðà—[’[‘]”]ˆ
Ø�jÐ Ð Ý"1°*¸WÔ2EÈÐPUÀÕXbÔXrÑ"sÔ"sˆJ�wÑØ�jÐ Ð Ý",Ô"<¸ZÈÔ=PÑ"QÔ"QˆJ�wÑØ˜*Ð$Ñ$Ø" ;Ô/×5Ò5Ñ7Ô7ˆIØ Ô'¨!Ò+ˆGØ!&¨¡¨i¸Ô.?Ñ ?ˆI�fÑØ!˜×,Ò,¨RÑ0Ô0ˆIØ!*¨3°°°¨7Ô!3×!?Ò!?À	È3Ñ!OÔ!OˆI�c˜2˜A˜2�gÑØÔ'ð 2ØÔ0�Ý�E )¤/°!Ô"4Ñ5Ô5Ñ6Ô6�Ý˜q¥# e¡*¤*¨aÑ0Ô0ð @ð @�AØ" 1œX u¨Q°©U¤|˜�BØ˜IœO¨AÔ.Ò.Ð.°2¸	¼ÈÔ8JÒ3JÐ3JØ-1°"¬X°t¸B´xÐ*˜˜R™ $ r¡(øØ% a a a¨¨q¨q¨q jÔ1�	Ý&?À	È6ÐSXÑ&YÔ&YˆJ�{Ñ#Ø�jÐ Ð r#   )rj   N)rm   r+   rÄ   rÅ   r   rn   rp   rx   ry   r@   r#   r!   rÃ   rÃ   ã  sW   € € € € € ðð ð(ð ð ð ð ð UYð(!ð (!ð (!ð (!ð (!ð (!ð (!r#   rÃ   rs   rÀ   rÁ   rt   c                óŒ  ‡‡‡‡— t          | ¦  «        \  }}t          j        | ‰‰‰‰¬¦  «        } |€| dfS |                     ¦   «         }d|v rmt	          |d         ||fˆˆˆˆfd„¦  «        }	|	dd…df         |	dd…df         k    |	dd…df         |	dd…df         k    z  }
|	|
         }t          ||
|¦  «        }d	|v r"t          j        |d	         ‰‰‰‰¬¦  «        |d	<   d
|v rN|d
                              ¦   «         }|dxx         ‰z  cc<   |dxx         ‰z  cc<   t          |‰‰¦  «        |d
<   | t          |‰‰¦  «        fS )uö  Crop an image and associated spatial target fields.

    Note:
        ``torchvision.transforms.v2.functional.crop`` crops an image/tv_tensor but has no
        annotation-dict awareness: it doesn't drop boxes that fall entirely outside the crop,
        filter per-instance fields (``labels``, ``area``, ``iscrowd``, ``masks``, ...) to match
        the surviving boxes, offset keypoints, or update ``size``. In particular ``labels`` is
        filtered per-instance alongside ``boxes`` (the ``keep`` mask is applied identically to
        both) so box/label correspondence is preserved â€” see
        ``tests/datasets/test__torchvision.py::TestCropFunction``. This function wraps the native
        crop for image/box (via :func:`_apply_to_boxes`) /mask geometry and adds that annotation
        bookkeeping on top.

    Args:
        image: Input image.
        target: Optional target dictionary.
        top: Crop top coordinate.
        left: Crop left coordinate.
        height: Crop height.
        width: Crop width.

    Returns:
        Cropped image and target.

    Examples:
        >>> from PIL import Image
        >>> img = Image.new("RGB", (100, 100))
        >>> cropped_img, cropped_target = crop(img, None, top=0, left=0, height=50, width=50)
    ©rÀ   rÁ   r    r   Nr   c                ó6   •— t          j        | ‰‰‰‰¬¦  «        S )NrÒ   )r   rº   )r   r    rÁ   rÀ   r   s    €€€€r!   r®   zcrop.<locals>.<lambda>Z  s   ø€ �*œ/¨%°S¸tÈFÐZ_Ð`Ñ`Ô`€ r#   rG   r   rH   r>   r3   rX   r[   r\   )	r"   r   rº   rI   r2   rW   r`   rd   rg   )r   r9   rÀ   rÁ   r    r   Úorig_heightÚ
orig_widthrS   Úcroppedr;   r   rX   s     ````       r!   rº   rº   +  s¨  øøøø€ õJ *¨%Ñ0Ô0Ñ€K�ÝŒO˜E s°¸fÈEÐRÑRÔR€EØ€~Ø�dˆ{Ðà—’‘”€JØ�*ÐÐÝ!Ø�wÔØ˜*Ð%Ø`Ð`Ð`Ð`Ð`Ð`Ð`ñ
ô 
ˆð
 ˜˜˜˜1˜” ¨¨¨¨1¨¤Ò-°'¸!¸!¸!¸Q¸$´-À'È!È!È!ÈQÈ$Ä-Ò2OÑPˆØ˜”ˆÝ0°¸TÀ5ÑIÔIˆ
Ø�*ÐÐÝ(œo¨j¸Ô.AÀsÐQUÐ^dÐlqÐrÑrÔrˆ
�7ÑØ�jÐ Ð Ø˜{Ô+×1Ò1Ñ3Ô3ˆ	Ø�&ÐÐÔ˜TÑ!ÐÐÑØ�&ÐÐÔ˜SÑ ÐÐÑÝ";¸IÀvÈuÑ"UÔ"Uˆ
�;ÑØ•,˜z¨6°5Ñ9Ô9Ð9Ð9r#   )r   r   r   r   )r   r$   r%   r   r&   r   r   r$   )r3   r$   r&   r   r   r$   )r9   r:   r;   r$   r   r$   r   r:   )rX   r$   r    r   r   r   r   r$   )r9   r:   r    r   r   r   r   r:   )r   r   r9   rs   rÀ   r   rÁ   r   r    r   r   r   r   rt   )-r}   Ú
__future__r   Úcollections.abcr   Útypingr   r   r   r   r	   r
   r.   ÚPILr   Útorchvisionr   Útorchvision.transformsr   Útorchvision.transforms.v2r   Úrfdetr.datasets._aug_utilsr   Ú	frozensetrM   r/   r   Ú__annotations__rP   r   r   r"   r2   r8   rW   rd   rg   ri   r   rŒ   r‘   r›   r¶   rÃ   rº   r@   r#   r!   ú<module>rá      s(  ððð ð ð #Ð "Ð "Ð "Ð "Ð "à $Ð $Ð $Ð $Ð $Ð $Ø >Ð >Ð >Ð >Ð >Ð >Ð >Ð >Ð >Ð >Ð >Ð >Ð >Ð >Ð >Ð >à €€€Ø Ð Ð Ð Ð Ð Ø "Ð "Ð "Ð "Ð "Ð "Ø 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø 0Ð 0Ð 0Ð 0Ð 0Ð 0à @Ð @Ð @Ð @Ð @Ð @ð "˜	 7 )Ñ,Ô,Ð/HÑHÐ Øœ u¤|Ñ3€Ð 3Ð 3Ð 3Ñ 3Ø˜d 3¨ 8œnÔ-€Ð -Ð -Ð -Ñ -Ø# K°Ð$8Ô9Ð Ð 9Ð 9Ð 9Ñ 9ð6ð 6ð 6ð 6ðEð Eð Eð Eð&Eð Eð Eð Eð&ð ð ð ð8ð ð ð ð2ð ð ð ð 'Fð 'Fð 'Fð 'Fð 'Fñ 'Fô 'Fð 'FðT%Mð %Mð %Mð %Mð %Mñ %Mô %Mð %MðP#ð #ð #ð #ð #ñ #ô #ð #ðLF%ð F%ð F%ð F%ð F%ñ F%ô F%ð F%ðRIFð IFð IFð IFð IFñ IFô IFð IFðX-0ð -0ð -0ð -0ð -0ñ -0ô -0ð -0ð`E!ð E!ð E!ð E!ð E!ñ E!ô E!ð E!ðP;:ð ;:ð ;:ð ;:ð ;:ð ;:r#   