§
    ­¸j;Æ  ã                  óú  — U d Z ddlmZ ddlmZ ddlmZmZ ddlZddlm	Z	 ddl
mZ ddlmZ dd	lmZ  e¦   «         Zd
dgiZdZdZdZded<   dZded<   dcd„Zddœddd„Zded „Zdfd"„Zddœdgd$„Zdhd%„Zdhd&„Zdid*„Zdjdkd/„Zdld2„Z dld3„Z!dld4„Z"dld5„Z#d6Z$did7„Z%dld8„Z&dld9„Z'dld:„Z(dld;„Z)dld<„Z*dld=„Z+dld>„Z,dld?„Z-dld@„Z.didA„Z/dldB„Z0dCZ1dldD„Z2e e!e"e#e&e'e(e)e*e+e,e-e.e0e2dEœZ3dFedG<   	 	 dmdndN„Z4eefdodR„Z5dpdX„Z6dqd]„Z7	 djdrdb„Z8dS )sab  Kornia-based GPU augmentation pipeline for RF-DETR training.

This module provides GPU-side augmentation as an alternative to the CPU-based Albumentations pipeline.  All transforms
run on the device where the batch already resides (typically CUDA), avoiding a CPU-GPU round-trip per sample.

Supports detection (boxes only) and segmentation (boxes + instance masks).

Usage::

    from rfdetr.datasets.kornia_transforms import (
        build_kornia_pipeline,
        build_normalize,
        collate_boxes,
        collate_masks,
        unpack_boxes,
    )

    # Detection:
    pipeline = build_kornia_pipeline(aug_config, resolution=560)
    normalize = build_normalize()
    boxes_padded, valid = collate_boxes(targets, device)
    img_aug, boxes_aug = pipeline(img, boxes_padded)
    img_aug = normalize(img_aug)
    targets = unpack_boxes(boxes_aug, valid, targets, H, W)

    # Segmentation (Phase 2):
    pipeline = build_kornia_pipeline(aug_config, resolution=560, with_masks=True)
    normalize = build_normalize()
    boxes_padded, valid = collate_boxes(targets, device)
    masks_padded = collate_masks(targets, device, n_max=valid.shape[1], image_height=H, image_width=W)
    img_aug, boxes_aug, masks_aug = pipeline(img, boxes_padded, masks_padded)
    img_aug = normalize(img_aug)
    targets = unpack_boxes(boxes_aug, valid, targets, H, W, masks_aug=masks_aug)
é    )Úannotations)ÚCallable)ÚAnyÚcastN)ÚTensor)ÚAugmentationBackend)Ú#filter_keypoint_hflip_augmentations)Ú
get_loggerÚbuild_kornia_pipelineÚkornia)g
×£p=
ß?gÉv¾Ÿ/Ý?g–C‹lçûÙ?)gZd;ßOÍ?gyé&1¬Ì?gÍÌÌÌÌÌÌ?)é   é   ztuple[int, int]Ú"_ALBUMENTATIONS_BLUR_LIMIT_DEFAULTç      à?ÚfloatÚ_MASK_BINARIZE_THRESHOLDÚreturnÚboolc                 óR   — ddl m}  t          | ¦  «                             d¦  «        S )aÄ  Return ``True`` when the runtime has a CUDA accelerator available.

    Uses the fork-safe global ``DEVICE`` constant from ``rfdetr.config`` so that the CUDA driver context is not created
    in the main process before forking (fork-based DDP and some notebook environments).

    Returns:
        ``True`` if at least one CUDA device is reachable; ``False`` otherwise.

    Examples:
        >>> _has_cuda_device()  # doctest: +SKIP
        False
    r   ©ÚDEVICEÚcuda)Úrfdetr.configr   ÚstrÚ
startswithr   s    úq/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/datasets/kornia_transforms.pyÚ_has_cuda_devicer   J   s0   € ð %Ð$Ð$Ð$Ð$Ð$åˆv‰;Œ;×!Ò! &Ñ)Ô)Ð)ó    ©Úhas_cudaÚbackendr   r    úbool | Noner   c               óŒ   — | t           j        ddfv rt          ¦   «          |€t          ¦   «         }t          j        | |¬¦  «        S )u#
  Resolve an ``augmentation_backend`` value to a concrete :class:`AugmentationBackend`.

    Auto-pick priority (for ``"cpu"``/``"auto"``) is implemented by
    :meth:`AugmentationBackend.from_str`; this function supplies the fork-safe CUDA check that
    gates ``"auto"``'s GPU-Kornia preference and fails fast when ``"albumentations"``/``"albu"``
    is explicitly requested but Albumentations is not installed.

    This is a pure resolution step â€” explicit ``"kornia"``/``"gpu"`` requests always pass through
    to :attr:`AugmentationBackend.KORNIA` regardless of *has_cuda*, so a saved/forced concrete
    backend resolves deterministically. Callers that need to fail fast when an explicit GPU
    request cannot actually run (no CUDA device, or Kornia not installed) should additionally call
    :func:`require_gpu_backend_ready` before building anything that depends on the result.

    Note:
        ``"cpu"`` and ``"auto"`` resolution depends on which optional packages happen to be
        installed (Albumentations and/or Kornia are both optional, via ``pip install
        'rfdetr[augment]'``). The same ``backend`` value can therefore resolve to a different
        concrete backend across environments â€” e.g. CI without ``[augment]`` installed resolves
        to ``TV`` (torchvision), while a local dev environment with Albumentations installed
        resolves to ``ALBU``. Pass ``"torchvision"`` explicitly to guarantee torchvision
        regardless of environment.

    Args:
        backend: One of ``"cpu"``, ``"auto"``, ``"torchvision"``, ``"albumentations"``,
            ``"kornia"``, or legacy ``"tv"``/``"albu"``/``"gpu"``.
        has_cuda: Whether a CUDA device is available. When ``None`` (default), computed via this
            module's fork-safe :func:`_has_cuda_device`. Callers with their own fork-safe CUDA
            check (e.g. :mod:`rfdetr.training.module_data`) may pass it explicitly so patching
            their own check affects resolution.

    Returns:
        Resolved :class:`AugmentationBackend` member.

    Raises:
        ValueError: When *backend* is not a recognised value.
        ImportError: When *backend* is explicitly ``"albumentations"``/``"albu"`` but
            Albumentations is not installed.

    Examples:
        >>> resolve_augmentation_backend("albumentations")
        <AugmentationBackend.ALBU: 'albumentations'>
        >>> resolve_augmentation_backend("kornia")
        <AugmentationBackend.KORNIA: 'kornia'>
        >>> resolve_augmentation_backend("torchvision")
        <AugmentationBackend.TV: 'torchvision'>
    ÚalbumentationsÚalbuNr   )r   ÚALBUÚ_require_albur   Úfrom_str)r!   r    s     r   Úresolve_augmentation_backendr)   \   sL   € ð^ Õ&Ô+Ð-=¸vÐFÐFÐFÝ‰ŒˆØÐÝ#Ñ%Ô%ˆÝÔ'¨¸(ÐCÑCÔCÐCr   Úrequested_backendÚNonec               ór   — | t           j        ddfvrdS |st          d| ›d�¦  «        ‚t          ¦   «          dS )uø  Fail fast when an explicit Kornia/GPU backend request cannot run in this environment.

    Only gates explicit ``"kornia"``/``"gpu"`` requests. ``"auto"``/``"cpu"`` silently fall back to
    the best installed CPU backend elsewhere (see :func:`resolve_augmentation_backend`) and are
    never gated here â€” an unavailable GPU is not an error for those sentinels, only for a backend
    the caller explicitly pinned to Kornia.

    Args:
        requested_backend: Raw ``augmentation_backend`` value as configured by the caller, before
            legacy-alias/auto-pick resolution.
        has_cuda: Whether a CUDA device is available, as determined by the caller's own fork-safe
            check.

    Raises:
        RuntimeError: ``kornia``/``gpu`` is explicitly requested but no CUDA device is available.
        ImportError: ``kornia``/``gpu`` is explicitly requested, CUDA is available, but Kornia is
            not installed.

    Examples:
        >>> require_gpu_backend_ready("cpu", has_cuda=False)
    r   ÚgpuNzaugmentation_backend=z/ requires a CUDA device, but none is available.)r   ÚKORNIAÚRuntimeErrorÚ_require_kornia©r*   r    s     r   Úrequire_gpu_backend_readyr2   ’   sU   € ð, Õ!4Ô!;¸XÀuÐ MÐMÐMØˆØð yÝÐwÐ3DÐwÐwÐwÑxÔxÐxÝÑÔÐÐÐr   Úresolvedc                ó"   — | t           j        k    S )aL  Return ``True`` when the resolved backend defers augmentation/normalization to the GPU.

    Kornia is the only on-device (GPU) backend, so a resolved backend of :attr:`AugmentationBackend.KORNIA`
    means the CPU dataset pipeline must skip its Albumentations augmentation wrappers and ``Normalize`` step
    (both are applied later on-device). ``TV`` and ``ALBU`` keep the full CPU pipeline.

    This is the single source of truth for the ``gpu_postprocess`` flag threaded through every dataset builder;
    call it instead of re-writing ``resolved == AugmentationBackend.KORNIA`` inline so the predicate stays in one
    place.

    Args:
        resolved: A concrete backend as returned by :func:`resolve_augmentation_backend` or
            :func:`resolve_backend_for_build`.

    Returns:
        ``True`` when *resolved* is Kornia (GPU postprocessing), ``False`` otherwise.

    Examples:
        >>> from rfdetr.config import AugmentationBackend
        >>> is_gpu_postprocess(AugmentationBackend.KORNIA)
        True
        >>> is_gpu_postprocess(AugmentationBackend.TV)
        False
    )r   r.   )r3   s    r   Úis_gpu_postprocessr5   ¯   s   € ð2 Õ*Ô1Ò1Ð1r   ústr | AugmentationBackendc               óf   — |€t          ¦   «         }t          | |¬¦  «         t          | |¬¦  «        S )u<  Fail fast, then resolve, an ``augmentation_backend`` value in one call for dataset builders.

    Bundles the two steps every dataset builder must perform before wiring ``gpu_postprocess``:

    1. :func:`require_gpu_backend_ready` â€” raise immediately when an explicit ``"kornia"``/``"gpu"`` request
       cannot actually run in this environment (no CUDA device, or Kornia not installed).
    2. :func:`resolve_augmentation_backend` â€” map the (possibly sentinel/legacy) value to a concrete
       :class:`AugmentationBackend` member.

    Combining them here makes the fail-fast structural rather than something each builder must remember to call
    separately, so a builder cannot silently skip the readiness check. Both steps share a single *has_cuda*
    value, computed once.

    Args:
        requested_backend: Raw ``augmentation_backend`` value as configured by the caller, before
            legacy-alias/auto-pick resolution â€” e.g. ``"cpu"``, ``"auto"``, ``"torchvision"``,
            ``"kornia"``, or legacy ``"gpu"``/``"tv"``/``"albu"``.
        has_cuda: Whether a CUDA device is available. When ``None`` (default), computed once via this
            module's fork-safe :func:`_has_cuda_device` and reused for both steps.

    Returns:
        Resolved :class:`AugmentationBackend` member.

    Raises:
        RuntimeError: ``"kornia"``/``"gpu"`` is explicitly requested but no CUDA device is available.
        ImportError: ``"kornia"``/``"gpu"`` is explicitly requested (with CUDA) but Kornia is not installed,
            or ``"albumentations"``/``"albu"`` is explicitly requested but Albumentations is not installed.
        ValueError: When *requested_backend* is not a recognised value.

    Examples:
        >>> resolve_backend_for_build("torchvision", has_cuda=False)
        <AugmentationBackend.TV: 'torchvision'>
    Nr   )r   r2   r)   r1   s     r   Úresolve_backend_for_buildr8   Ë   s>   € ðL ÐÝ#Ñ%Ô%ˆÝÐ/¸(ÐCÑCÔCÐCÝ'Ð(9ÀHÐMÑMÔMÐMr   c                 ó`   — t           j                             ¦   «         st          d¦  «        ‚dS )zžVerify that Kornia is importable, raising a clear error if not.

    Raises:
        ImportError: When ``kornia`` is not installed, with an install hint.
    zMGPU augmentation requires kornia. Install with: pip install 'rfdetr[augment]'N)r   r.   Ú_is_availableÚImportError© r   r   r0   r0   ÷   s7   € õ Ô%×3Ò3Ñ5Ô5ð kÝÐiÑjÔjÐjðkð kr   c                 ó`   — t           j                             ¦   «         st          d¦  «        ‚dS )z®Verify that Albumentations is importable, raising a clear error if not.

    Raises:
        ImportError: When ``albumentations`` is not installed, with an install hint.
    zgCustom Albumentations augmentations require albumentations. Install with: pip install 'rfdetr[augment]'N)r   r&   r:   r;   r<   r   r   r'   r'     s:   € õ Ô#×1Ò1Ñ3Ô3ð 
ÝØuñ
ô 
ð 	
ð
ð 
r   Úvaluer   útuple[float, float]c                ó®  — t          | t          t          f¦  «        rœt          | ¦  «        dk    r*t	          | d         ¦  «        t	          | d         ¦  «        fS t          | ¦  «        dk    r*t	          | d         ¦  «        t	          | d         ¦  «        fS t          dt          | ¦  «        › d| ›�¦  «        ‚t	          | ¦  «        t	          | ¦  «        fS )aÊ  Normalise a scalar-or-pair config value to a ``(min, max)`` tuple.

    Albumentations accepts either form for range parameters such as ``sigma`` and ``std_range``, so the builders below
    take both rather than raising a bare ``TypeError`` from inside Kornia on a config that is valid for the CPU path.
    :func:`_make_rotate` also accepts a scalar or a pair for ``limit``, but with different scalar semantics: it
    expands a scalar ``v`` symmetrically to ``(-v, v)``, whereas this helper expands it to the degenerate ``(v, v)``.

    Args:
        value: A scalar, a 1-element sequence (a degenerate ``(v, v)`` range), or a 2-element ``(min, max)`` pair.

    Returns:
        The value as a ``(min, max)`` float pair: ``(v, v)`` for a scalar or 1-element sequence, ``(min, max)`` for a
        pair.

    Raises:
        ValueError: If ``value`` is an empty sequence or has more than two elements, rather than silently dropping
            trailing elements.
    é   r   é   z^Range parameter must be a scalar, a 1-element sequence, or a 2-element (min, max) pair; got a ú-element sequence: )Ú
isinstanceÚlistÚtupleÚlenr   Ú
ValueError©r>   s    r   Ú	_as_rangerJ     sÆ   € õ& �%�$¥˜Ñ'Ô'ð 
Ýˆu‰:Œ:˜Š?ˆ?Ý˜% œ(‘O”O¥U¨5°¬8¡_¤_Ð5Ð5Ýˆu‰:Œ:˜Š?ˆ?Ý˜% œ(‘O”O¥U¨5°¬8¡_¤_Ð5Ð5Ýð>Ý˜‘Z”Zð>ð >Ø49ð>ð >ñ
ô 
ð 	
õ �%‰LŒL�% ™,œ,Ð'Ð'r   Ú	transformÚdefault_pairútuple[int, int] | NoneÚintc                ó>  — d}t          | t          t          f¦  «        rƒt          | ¦  «        dk    r	| d         } ngt          | ¦  «        dk    r2| d         | d         k    r| d         | d         f}t	          | ¦  «        } n"t          dt          | ¦  «        › d| ›�¦  «        ‚t          | ¦  «        }|dz  dk    r|dz  }t	          d|¦  «        }|�L|duo|t          |¦  «        k    }|rt          j        nt          j	        } |d|||d         |d         ¦  «         |S )	aø  Resolve an Albumentations ``blur_limit`` to a single odd Kornia kernel size.

    Albumentations samples an odd kernel from a ``(min, max)`` range per call; Kornia takes one fixed kernel size, so a
    non-degenerate pair collapses to its upper bound and the divergence is logged. The result is forced odd and at
    least 3, which Kornia requires, and to an ``int``: a float such as ``5.0`` builds but crashes at forward time.

    Args:
        value: A scalar kernel size, a 1-element sequence (a degenerate single kernel size), or a ``(min, max)`` pair.
        transform: Name used in the log message, so the log says which augmentation collapsed.
        default_pair: The Albumentations default range for ``transform``, when its default is a range rather than a
            scalar. A ``value`` equal to it is the library default rather than a deliberate user choice, so its
            collapse is logged at ``DEBUG``; every other non-degenerate pair is an explicit request the GPU path
            cannot honor and stays at ``WARNING``.

    Returns:
        An odd ``int`` kernel size of at least 3.

    Raises:
        ValueError: If ``value`` is an empty sequence or has more than two elements, rather than silently dropping
            trailing elements.
    NrA   r   rB   zdKernel size parameter must be a scalar, a 1-element sequence, or a 2-element (min, max) pair; got a rC   r   z¶GPU augmentation (Kornia) uses a fixed kernel_size=%d for %s (Kornia does not sample the kernel size per call). CPU augmentation (albumentations) samples an odd kernel from [%s, %s].)
rD   rE   rF   rG   ÚmaxrH   rN   ÚloggerÚdebugÚwarning)r>   rK   rL   Úcollapsed_fromÚkernelÚis_library_defaultÚlogs          r   Ú_as_odd_kernelrX   1  sW  € ð, .2€NÝ�%�$¥˜Ñ'Ô'ð Ýˆu‰:Œ:˜Š?ˆ?Ø˜!”HˆEˆEÝ�‰ZŒZ˜1Š_ˆ_Ø�QŒx˜5 œ8Ò#Ð#Ø"'¨¤(¨E°!¬HÐ!5�Ý˜‘J”JˆEˆEåðBÝ˜U™œðBð BØ8=ðBð Bñô ð õ �‰ZŒZ€FØ��z�Q‚€Ø�!‰ˆÝ��F‰^Œ^€FØÐ!ð *°Ð5Ð_¸.ÍEÐR^ÑL_ÔL_Ò:_ÐØ0ÐD�fŒlˆlµf´nˆØˆðUð ØØ˜1ÔØ˜1Ôñ	
ô 	
ð 	
ð €Mr   Úparamsúdict[str, Any]c                óN   — ddl m}  ||                      dd¦  «        ¬¦  «        S )z:Build a ``K.RandomHorizontalFlip`` from aug_config params.r   )ÚRandomHorizontalFlipÚpr   ©r]   )Úkornia.augmentationr\   Úget)rY   r\   s     r   Ú_make_horizontal_flipra   j  s6   € à8Ð8Ð8Ð8Ð8Ð8àÐ &§*¢*¨S°#Ñ"6Ô"6Ð7Ñ7Ô7Ð7r   c                óN   — ddl m}  ||                      dd¦  «        ¬¦  «        S )z8Build a ``K.RandomVerticalFlip`` from aug_config params.r   )ÚRandomVerticalFlipr]   r   r^   )r_   rc   r`   )rY   rc   s     r   Ú_make_vertical_fliprd   q  s6   € à6Ð6Ð6Ð6Ð6Ð6àÐ §
¢
¨3°Ñ 4Ô 4Ð5Ñ5Ô5Ð5r   c                ó>  — ddl m} |                      dd¦  «        }t          |t          t
          f¦  «        rt          |¦  «        n| |f} |||                      dd¦  «        ¬¦  «        }t          |dd	¦  «        }t          |t          ¦  «        r	d
|vr||d
<   |S )z„Build a ``K.RandomRotation`` from aug_config params.

    The ``limit`` parameter may be a scalar (symmetric range) or a tuple.
    r   )ÚRandomRotationÚlimité   r]   r   )Údegreesr]   ÚflagsNri   )r_   rf   r`   rD   rE   rF   ÚgetattrÚdict)rY   rf   rg   ri   Úrotationrj   s         r   Ú_make_rotatern   x  s±   € ð
 3Ð2Ð2Ð2Ð2Ð2à�JŠJ�w Ñ#Ô#€EÝ(¨µµu°Ñ>Ô>ÐS�e�E‰lŒlˆlÀeÀVÈUÀO€GØˆ~ g°·²¸CÀÑ1EÔ1EÐFÑFÔF€Hõ
 �H˜g tÑ,Ô,€EÝ�%�ÑÔð # 9°EÐ#9Ð#9Ø"ˆˆiÑà€Or   c           
     ó  — ddl m} |                      d¦  «        }t          |t          t
          f¦  «        r?t          |t          ¦  «        s*t                               d|¦  «         t          |¦  «        }t          |t          t          f¦  «        rNt          |¦  «        dk    r;t          t          |d         ¦  «        t          |d         ¦  «        ¦  «        }||f}n|}|                      d¦  «        }t          |t          t
          f¦  «        r$t          |t          ¦  «        st          |¦  «        } ||                      dd	¦  «        |||                      d
¦  «        |                      dd¦  «        ¬¦  «        S )aY  Build a ``K.RandomAffine`` from aug_config params.

    Albumentations ``translate_percent`` accepts a scalar or a ``(min, max)`` signed range. Kornia ``translate`` is a
    non-negative per-axis max fraction ``(tx, ty)`` where translation is sampled from ``[-tx, tx]``. The conversion
    takes ``max(|min|, |max|)`` for each axis. A scalar cannot preserve Albumentations' fixed positive translation, so
    this builder warns before approximating it with symmetric signed sampling. Albumentations ``scale`` also accepts a
    scalar, while Kornia requires a range, so scalars become ``(v, v)``.
    r   ©ÚRandomAffineÚtranslate_percenta  GPU augmentation (Kornia) Affine scalar translate_percent=%s samples signed translations on both axes; CPU augmentation (albumentations) applies a fixed positive translation, so this is a different distribution. Use the albumentations backend when the exact distribution matters.rB   rA   ÚscaleÚrotate)iñÿÿÿrh   Úshearr]   r   )ri   Ú	translaters   ru   r]   )r_   rq   r`   rD   rN   r   r   rQ   rS   Ú_as_symmetric_rangerE   rF   rG   rP   ÚabsrJ   )rY   rq   rr   Ú	magnituderv   rs   s         r   Ú_make_affinerz   �  s„  € ð 1Ð0Ð0Ð0Ð0Ð0àŸ
š
Ð#6Ñ7Ô7ÐÝÐ#¥c­5 \Ñ2Ô2ð C½:ÐFWÕY]Ñ;^Ô;^ð CÝ�Šð`ð ñ		
ô 	
ð 	
õ 0Ð0AÑBÔBÐÝÐ#¥d­E ]Ñ3Ô3ð &½Ð<MÑ8NÔ8NÐRSÒ8SÐ8SÝ�Ð-¨aÔ0Ñ1Ô1µ3Ð7HÈÔ7KÑ3LÔ3LÑMÔMˆ	ØGPÐR[ÐF\ˆ	ˆ	à%ˆ	à�JŠJ�wÑÔ€EÝ�%�#�u˜Ñ&Ô&ð !­z¸%ÅÑ/FÔ/Fð !Ý˜%Ñ Ô ˆàˆ<Ø—
’
˜8 YÑ/Ô/ØØØ�jŠj˜Ñ!Ô!Ø
�*Š*�S˜#Ñ
Ô
ðñ ô ð r   )ÚinterpolationÚborder_modeÚmask_interpolationÚfillÚ	fill_maskÚrotate_methodc                ó–   — t          | t          t          f¦  «        rt          | ¦  «        S t	          | ¦  «         t	          | ¦  «        fS )a  Normalise an Albumentations ``*_limit`` value to a ``(min, max)`` pair.

    These parameters expand a scalar ``v`` symmetrically to ``(-v, v)`` rather than to the degenerate ``(v, v)``
    :func:`_as_range` produces, so they need their own normalisation.
    )rD   rE   rF   rJ   r   rI   s    r   rw   rw   ¿  sA   € õ �%�$¥˜Ñ'Ô'ð  Ý˜ÑÔÐÝ�5‰\Œ\ˆM�5 ™<œ<Ð(Ð(r   c           	     ó   ‡ — ddl m} ˆ fd„t          D ¦   «         }|r8t                               dd                     d„ |D ¦   «         ¦  «        ¦  «         t          ‰                      dd¦  «        ¦  «        }‰                      d	¦  «        }‰                      d
¦  «        }|�t          |¦  «        n|}|�t          |¦  «        n|}d|d‰ v fd	||dufd
||duff}d„ |D ¦   «         }	|	r8t                               dd                     d„ |	D ¦   «         ¦  «        ¦  «         t          t          |d         ¦  «        t          |d         ¦  «        ¦  «        t          t          |d         ¦  «        t          |d         ¦  «        ¦  «        f}
t          ‰                      dd¦  «        ¦  «        \  }} |t          ‰                      dd¦  «        ¦  «        |
d|z   d|z   f‰                      dd¦  «        ¬¦  «        S )aÉ  Build a ``K.RandomAffine`` from aug_config ``ShiftScaleRotate`` params.

    Albumentations itself calls this "a special case of Affine transform" and deprecates it in favour of ``Affine``,
    which this backend already supports. It is mapped anyway because the CPU path still accepts the name, so a config
    using it trains on a CPU box and raises on a GPU box; new configs should prefer ``Affine``.

    The three limits do **not** pass through to :func:`_make_affine`'s parameters unchanged, which is the whole reason
    this needs its own builder rather than an alias:

    - ``scale_limit`` is a delta biased by 1, not an absolute multiplier. Albumentations samples from
      ``(1 + low, 1 + high)``, so the documented default ``(-0.1, 0.1)`` means a scale between ``0.9`` and ``1.1``.
      Kornia's ``scale`` is the absolute multiplier range, so the pivot is applied here. Forwarding the raw value
      would ask Kornia to scale the image to between a tenth of its size and nothing at all. This is the same
      1.0-pivot that :func:`_make_sharpen` applies to ``alpha``.
    - ``shift_limit`` is a signed fraction range, while Kornia's ``translate`` is a non-negative per-axis maximum
      sampled symmetrically, so it is converted the same way :func:`_make_affine` converts ``translate_percent``.
      ``shift_limit_x`` and ``shift_limit_y`` override it per axis, with ``None`` preserving the shared limit as it
      does on the Albumentations backend. Kornia cannot represent an asymmetric shift interval, so this builder uses
      the greatest absolute bound and logs that distributional approximation.
    - all three accept a scalar as a symmetric range, unlike the ``(v, v)`` reading :func:`_as_range` gives.
    r   rp   c                ó   •— g | ]}|‰v ¯|‘Œ	S r<   r<   ©Ú.0ÚkrY   s     €r   ú
<listcomp>z,_make_shift_scale_rotate.<locals>.<listcomp>â  s   ø€ ÐJÐJÐJ�Q¸aÀ6¸k¸kˆq¸k¸k¸kr   z£GPU augmentation (Kornia) ShiftScaleRotate ignores %s (Kornia's RandomAffine exposes only the geometric parameters). CPU augmentation (albumentations) honors them.ú, c              3  ó4   K  — | ]}t          |¦  «        V — Œd S ©N©Úrepr©r…   r†   s     r   ú	<genexpr>z+_make_shift_scale_rotate.<locals>.<genexpr>è  ó(   è è € Ð/Ð/ !•d˜1‘g”gÐ/Ð/Ð/Ð/Ð/Ð/r   Úshift_limit)g      °¿g      °?Úshift_limit_xÚshift_limit_yNc                óD   — g | ]\  }}}|r|d          |d          k    ¯|‘ŒS )r   rA   r<   )r…   ÚnameÚboundsÚis_configureds       r   r‡   z,_make_shift_scale_rotate.<locals>.<listcomp>õ  sG   € ð ð ð Ù,��v˜}À]ðØW]Ð^_ÔW`ÐekÐlmÔenÐdnÒWnÐWnˆÐWnÐWnÐWnr   zÇGPU augmentation (Kornia) ShiftScaleRotate approximates asymmetric %s with a symmetric range using the greatest absolute limit. CPU augmentation (Albumentations) preserves the requested distribution.c              3  ó4   K  — | ]}t          |¦  «        V — Œd S rŠ   r‹   )r…   r”   s     r   rŽ   z+_make_shift_scale_rotate.<locals>.<genexpr>ü  s(   è è € Ð?Ð? T•d˜4‘j”jÐ?Ð?Ð?Ð?Ð?Ð?r   rA   Úscale_limit)gš™™™™™¹¿çš™™™™™¹?Úrotate_limit)iÓÿÿÿé-   ç      ð?r]   r   )ri   rv   rs   r]   )
r_   rq   Ú _SHIFT_SCALE_ROTATE_IGNORED_KEYSrQ   rS   Újoinrw   r`   rP   rx   )rY   rq   ÚignoredÚshiftÚshift_x_valueÚshift_y_valueÚshift_xÚshift_yÚconfigured_limitsÚasymmetric_limitsrv   Ú	scale_lowÚ
scale_highs   `            r   Ú_make_shift_scale_rotater©   Ê  sC  ø€ ð, 1Ð0Ð0Ð0Ð0Ð0àJÐJÐJÐJÕ:ÐJÑJÔJ€GØð 
Ý�Šð=ð �IŠIÐ/Ð/ wÐ/Ñ/Ô/Ñ/Ô/ñ		
ô 	
ð 	
õ   §
¢
¨=Ð:KÑ LÔ LÑMÔM€EØ—J’J˜Ñ/Ô/€MØ—J’J˜Ñ/Ô/€MØ4AÐ4MÕ! -Ñ0Ô0Ð0ÐSX€GØ4AÐ4MÕ! -Ñ0Ô0Ð0ÐSX€Gà	˜˜}°Ð6Ð7Ø	˜' =¸Ð#<Ð=Ø	˜' =¸Ð#<Ð=ðÐð
ð Ø0Aðñ ô Ðð ð 
Ý�Šðsà�IŠIÐ?Ð?Ð->Ð?Ñ?Ô?Ñ?Ô?ñ	
ô 	
ð 	
õ 	�C�˜”
‰OŒO�S ¨¤™_œ_Ñ-Ô-Ý�C�˜”
‰OŒO�S ¨¤™_œ_Ñ-Ô-ð€Iõ
 0°·
²
¸=È+Ñ0VÔ0VÑWÔWÑ€Iˆzàˆ<Ý# F§J¢J¨~¸yÑ$IÔ$IÑJÔJØØ�Y‰  jÑ 0Ð1Ø
�*Š*�S˜#Ñ
Ô
ð	ñ ô ð r   c           
     óö   — ddl m}  ||                      dd¦  «        |                      dd¦  «        |                      dd¦  «        |                      dd¦  «        |                      dd	¦  «        ¬
¦  «        S )zàBuild a ``K.ColorJiggle`` from aug_config ``ColorJitter`` params.

    Note: Kornia >=0.7 uses ``ColorJiggle``; the ``ColorJitter`` alias was
    added in later versions.  We use ``ColorJiggle`` for broad compatibility.
    r   ©ÚColorJiggleÚ
brightnessç        ÚcontrastÚ
saturationÚhuer]   r   )r­   r¯   r°   r±   r]   ©r_   r¬   r`   ©rY   r¬   s     r   Ú_make_color_jitterr´     s„   € ð 0Ð/Ð/Ð/Ð/Ð/àˆ;Ø—:’:˜l¨CÑ0Ô0Ø—’˜J¨Ñ,Ô,Ø—:’:˜l¨CÑ0Ô0Ø�JŠJ�u˜cÑ"Ô"Ø
�*Š*�S˜#Ñ
Ô
ðñ ô ð r   c                ó’   — ddl m} d| v sd| v rt                               d¦  «          ||                      dd¦  «        ¬¦  «        S )	a¨  Build a ``K.RandomGrayscale`` from aug_config ``ToGray`` params.

    Matches Albumentations' ``ToGray``: the image is converted to grayscale and kept at three channels, so it stays a
    drop-in for an RGB pipeline. Only ``p`` is honored on this (Kornia) backend: ``method`` and ``num_output_channels``
    are accepted by the CPU (albumentations) path but have no Kornia equivalent, so they are silently ignored here.
    r   )ÚRandomGrayscaleÚmethodÚnum_output_channelszÈGPU augmentation (Kornia) ToGray ignores 'method' and 'num_output_channels' (Kornia's RandomGrayscale always uses BT.601 weights and returns 3 channels). CPU augmentation (albumentations) honors both.r]   r   r^   )r_   r¶   rQ   rS   r`   )rY   r¶   s     r   Ú_make_to_grayr¹     sj   € ð 4Ð3Ð3Ð3Ð3Ð3à�6ÐÐÐ2°fÐ<Ð<Ý�Šð=ñ	
ô 	
ð 	
ð
 ˆ?˜VŸZšZ¨¨SÑ1Ô1Ð2Ñ2Ô2Ð2r   c                ó¢   — ddl m}  ||                      dd¦  «        |                      dd¦  «        |                      dd¦  «        ¬¦  «        S )	zCBuild a ``K.ColorJiggle`` from ``RandomBrightnessContrast`` params.r   r«   Úbrightness_limitçš™™™™™É?Úcontrast_limitr]   r   )r­   r¯   r]   r²   r³   s     r   Ú _make_random_brightness_contrastr¾   0  sb   € à/Ð/Ð/Ð/Ð/Ð/àˆ;Ø—:’:Ð0°#Ñ6Ô6Ø—’Ð,¨cÑ2Ô2Ø
�*Š*�S˜#Ñ
Ô
ðñ ô ð r   c                óR  — ddl m} t          |                      dd¦  «        d¦  «        }d| v r	| d         }n>t          j                             ¦   «         rddl}|                     ¦   «         j	        }nd}t          |¦  «        } |||f||                      d	d
¦  «        ¬¦  «        S )a5  Build a ``K.RandomGaussianBlur`` from aug_config params.

    Both ``blur_limit`` and ``sigma`` accept a scalar or a ``(min, max)`` pair, since Albumentations accepts either and
    a config written for the CPU path should not fail here, but a pair resolves asymmetrically: ``blur_limit`` takes the
    pair's upper bound (Kornia uses a single kernel size), rounded up to an odd integer, while ``sigma`` is passed
    through as a real ``(min, max)`` range. A non-degenerate ``blur_limit`` pair therefore collapses to fixed maximum
    blur and logs a warning.
    r   )ÚRandomGaussianBlurÚ
blur_limitr   ÚGaussianBlurÚsigmaN)r™   g       @r]   r   )Úkernel_sizerÃ   r]   )r_   rÀ   rX   r`   r   r&   r:   r$   rÂ   Úsigma_limitrJ   )rY   rÀ   rÁ   Úsigma_ranger$   Ú
blur_sigmas         r   Ú_make_gaussian_blurrÈ   ;  sÎ   € ð 7Ð6Ð6Ð6Ð6Ð6õ   §
¢
¨<¸Ñ ;Ô ;¸^ÑLÔL€JØ�&ÐÐØ˜W”oˆˆõ
 Ô#×1Ò1Ñ3Ô3ð 	%Ø!Ð!Ð!Ð!à(×5Ò5Ñ7Ô7ÔCˆKˆKà$ˆKÝ˜;Ñ'Ô'€JØÐØ Ð,ØØ
�*Š*�S˜#Ñ
Ô
ðñ ô ð r   c                ó$  — ddl m} t          |                      dd¦  «        ¦  «        }|d         |d         k    r/t                               d|d         |d         |d         ¦  «          ||d         |                      dd¦  «        ¬	¦  «        S )
ay  Build a ``K.RandomGaussianNoise`` from aug_config params.

    Kornia takes a single ``std`` value, so the upper bound of ``std_range`` is used as a fixed standard deviation. When
    the configured range is non-degenerate this diverges from the CPU (albumentations) path, which samples a fresh std
    per call; a warning is emitted at build time so the drift is visible.
    r   )ÚRandomGaussianNoiseÚ	std_range)r¼   g)\�Âõ(Ü?rA   z­GPU augmentation (Kornia) uses fixed std=%.3f for GaussianNoise (Kornia does not support per-sample std ranges). CPU augmentation (albumentations) samples from [%.3f, %.3f].r]   r   )Ústdr]   )r_   rÊ   rJ   r`   rQ   rS   )rY   rÊ   rË   s      r   Ú_make_gauss_noiserÍ   \  s­   € ð 8Ð7Ð7Ð7Ð7Ð7õ
 ˜&Ÿ*š* [°+Ñ>Ô>Ñ?Ô?€IØ�„|�y ”|Ò#Ð#Ý�ŠðKð �aŒLØ�aŒLØ�aŒLñ	
ô 	
ð 	
ð ÐØ�aŒLØ
�*Š*�S˜#Ñ
Ô
ðñ ô ð r   c                ó´   — ddl m} t          |                      dt          ¦  «        dt          ¬¦  «        } |||f|                      dd¦  «        ¬¦  «        S )	aS  Build a ``K.RandomBoxBlur`` from aug_config ``Blur`` params.

    Albumentations' ``Blur`` is a box (average) blur, which is what ``RandomBoxBlur`` applies, so this is a direct
    mapping. ``blur_limit`` resolves the same way as for ``GaussianBlur``: a non-degenerate pair collapses to its upper
    bound because Kornia takes a single kernel size. Unlike ``GaussianBlur``, Albumentations' own default here is a
    range rather than a scalar, so the default collapse is expected rather than a misconfiguration and is reported at
    ``DEBUG``; a range the user set explicitly still warns.
    r   )ÚRandomBoxBlurrÁ   ÚBlur)rL   r]   r   )rÄ   r]   )r_   rÏ   rX   r`   r   )rY   rÏ   rU   s      r   Ú
_make_blurrÑ   x  sl   € ð 2Ð1Ð1Ð1Ð1Ð1åØ�
Š
�<Õ!CÑDÔDØÝ7ðñ ô €Fð
 ˆ= f¨fÐ%5¸¿ºÀCÈÑ9MÔ9MÐNÑNÔNÐNr   c                óð   — ddl m} d| v sd| v rt                               d¦  «         t	          |                      dd¦  «        ¦  «        \  }} |d|z   d|z   f|                      d	d
¦  «        ¬¦  «        S )aÙ  Build a ``K.RandomSharpness`` from aug_config ``Sharpen`` params.

    The two libraries use different origins for the same effect, so ``alpha`` is shifted rather than passed through.
    Albumentations' ``alpha`` is the visibility of the sharpened image: ``0`` leaves the image unchanged and ``1``
    shows the fully sharpened version, so it never blurs. Kornia's ``sharpness`` factor is pivoted at ``1.0`` (the
    PIL ``ImageEnhance.Sharpness`` convention): it blends from a smoothed copy at ``0`` through the untouched image
    at ``1.0`` and sharpens only above ``1.0``. Passing ``alpha`` through unchanged would therefore blur the image
    for every value below ``1``, so the resolved range is shifted with ``sharpness = 1.0 + alpha``, which keeps the
    Albumentations no-op at ``alpha = 0`` mapped to Kornia's no-op at ``sharpness = 1.0``.

    ``lightness`` and ``method`` have no Kornia equivalent and are ignored here; the CPU (albumentations) path honors
    both.
    r   )ÚRandomSharpnessÚ	lightnessr·   z­GPU augmentation (Kornia) Sharpen ignores 'lightness' and 'method' (Kornia's RandomSharpness exposes only a sharpness factor). CPU augmentation (albumentations) honors both.Úalpha)r¼   r   rœ   r]   r   )Ú	sharpnessr]   )r_   rÓ   rQ   rS   rJ   r`   )rY   rÓ   Ú	alpha_minÚ	alpha_maxs       r   Ú_make_sharpenrÙ   ‹  s¢   € ð 4Ð3Ð3Ð3Ð3Ð3à�fÐÐ ¨FÐ 2Ð 2Ý�Šð=ñ	
ô 	
ð 	
õ
 % V§Z¢Z°¸Ñ%DÔ%DÑEÔEÑ€IˆyØˆ?Ø˜‘? C¨)¡OÐ4Ø
�*Š*�S˜#Ñ
Ô
ðñ ô ð r   c                óº   ‡ — ddl m} t          ˆ fd„dD ¦   «         ¦  «        rt                               d¦  «          |‰                      dd¦  «        ¬¦  «        S )	a  Build a ``K.RandomEqualize`` from aug_config ``Equalize`` params.

    Only ``p`` is honored. ``mode``, ``by_channels`` and ``mask`` are accepted by the CPU (albumentations) path but
    have no Kornia equivalent: ``RandomEqualize`` always equalizes every channel and takes no mask.
    r   )ÚRandomEqualizec              3  ó    •K  — | ]}|‰v V — Œ	d S rŠ   r<   )r…   ÚkeyrY   s     €r   rŽ   z!_make_equalize.<locals>.<genexpr>°  s'   øè è € Ð
DÐ
D˜Sˆ3�&ˆ=Ð
DÐ
DÐ
DÐ
DÐ
DÐ
Dr   )ÚmodeÚby_channelsÚmaskzÅGPU augmentation (Kornia) Equalize ignores 'mode', 'by_channels' and 'mask' (Kornia's RandomEqualize always equalizes all channels and takes no mask). CPU augmentation (albumentations) honors them.r]   r   r^   )r_   rÛ   ÚanyrQ   rS   r`   )rY   rÛ   s   ` r   Ú_make_equalizerâ   ¨  s{   ø€ ð 3Ð2Ð2Ð2Ð2Ð2å
Ð
DÐ
DÐ
DÐ
DÐ$CÐ
DÑ
DÔ
DÑDÔDð 
Ý�Šð=ñ	
ô 	
ð 	
ð
 ˆ>˜FŸJšJ s¨CÑ0Ô0Ð1Ñ1Ô1Ð1r   c                ó  — t          | t          t          f¦  «        r`t          | ¦  «        dk    r#t	          dt          | ¦  «        › d| ›d�¦  «        ‚t          | d         ¦  «        t          | d         ¦  «        fS dt          | ¦  «        fS )a$  Normalise ``CLAHE``'s ``clip_limit`` the way Albumentations does.

    Albumentations applies ``to_tuple(clip_limit, low=1)``, so a scalar ``v`` means the range ``(1, v)``. This differs
    from :func:`_as_range`, which expands a scalar to the degenerate ``(v, v)``; using that here would change the
    distribution rather than the units.

    Args:
        value: A scalar, or a 2-element ``(min, max)`` pair.

    Returns:
        The ``(min, max)`` pair Albumentations would sample from for the same config.

    Raises:
        ValueError: If *value* is a sequence of any length other than two. Albumentations validates ``clip_limit`` as
            either a float or an exact 2-tuple and rejects ``[4.0]``, so accepting it here (as a scalar, via
            :func:`_as_range`) would make the same config train on the GPU backend and fail on the CPU one. The point
            of this helper is that the two agree.

    Examples:
        >>> _as_clahe_clip_limit(4.0)
        (1.0, 4.0)
        >>> _as_clahe_clip_limit((2.0, 6.0))
        (2.0, 6.0)
    rB   zHCLAHE clip_limit must be a scalar or a 2-element (min, max) pair; got a rC   ze. Albumentations rejects this too, so the CPU (albumentations) backend would fail on the same config.r   rA   rœ   )rD   rE   rF   rG   rH   r   rI   s    r   Ú_as_clahe_clip_limiträ   ¹  s�   € õ2 �%�$¥˜Ñ'Ô'ð 2Ýˆu‰:Œ:˜Š?ˆ?ÝðJÝ˜U™œðJð JØ8=ðJð Jð Jñô ð õ
 �e˜A”h‘”¥ u¨Q¤x¡¤Ð1Ð1à•�u‘”ÐÐr   c                óD  — ddl m} t          t          |¦  «        j        }|                      dd¦  «        } |t          |                      dd¦  «        ¦  «        t          |d         ¦  «        t          |d         ¦  «        f|                      dd	¦  «        ¬
¦  «        S )u|  Build a ``K.RandomClahe`` from aug_config ``CLAHE`` params.

    ``tile_grid_size`` becomes ``grid_size`` directly. ``clip_limit`` needs care: Albumentations reads a scalar ``v`` as
    the range ``(1, v)`` and samples from it, not as the fixed value ``v``. Passing it through :func:`_as_range` would
    produce the degenerate ``(v, v)`` and pin the GPU path to maximum contrast enhancement on every sample while the CPU
    path varied it â€” and since ``4.0`` is the default on both sides, that divergence applied to the default
    configuration rather than only to unusual ones. A pair is already a range and is used as given.
    r   NÚtile_grid_size)é   rç   Ú
clip_limitg      @rA   r]   r   )rè   Ú	grid_sizer]   )r_   Úaugmentationr   r   ÚRandomClaher`   rä   rN   )rY   Úkornia_augmentationÚrandom_claheÚgrids       r   Ú_make_claherï   Þ  sœ   € ð 6Ð5Ð5Ð5Ð5Ð5å�Ð0Ñ1Ô1Ô=€LØ�:Š:Ð&¨Ñ/Ô/€DØˆ<Ý'¨¯
ª
°<ÀÑ(EÔ(EÑFÔFÝ�t˜A”w‘<”<¥ T¨!¤W¡¤Ð.Ø
�*Š*�S˜#Ñ
Ô
ðñ ô ð r   )Ú
fit_outputr{   r}   r|   r~   r   c                óT  ‡ — ddl m} ‰                      d¦  «        du rt          d¦  «        ‚ˆ fd„t          D ¦   «         }|r8t
                               dd                     d	„ |D ¦   «         ¦  «        ¦  «         ‰                      d
d¦  «        }t          |t          t          f¦  «        rdt          |¦  «        fnt          |¦  «        }t
                               d|d         |d         |d         |d         ¦  «          ||d         ‰                      dd¦  «        ¬¦  «        S )aR  Build a ``K.RandomPerspective`` from aug_config ``Perspective`` params.

    Both libraries displace the corners by a fraction of the image side, but they do not sample that fraction the same
    way, so this is an approximation rather than a parameter rename. Albumentations treats ``scale`` as the standard
    deviation of a normal and takes ``abs(N(0, sigma))`` per corner (normalizing a scalar ``v`` to ``(0, v)``), so small
    displacements dominate and large ones are possible but rare. Kornia draws uniformly from ``[0, distortion_scale]``.
    Passing the upper bound of ``scale`` as ``distortion_scale`` keeps the worst-case distortion roughly aligned while
    making the typical distortion noticeably stronger on the GPU path; there is no setting that makes the two
    distributions equal. The divergence is logged so a run does not silently change character when it moves onto the
    GPU.

    Other Albumentations ``Perspective`` options (``fit_output``, ``interpolation``, ``mask_interpolation``,
    ``border_mode``, ``fill``, ``fill_mask``) have no ``RandomPerspective`` equivalent and are ignored with a warning
    when set to a non-default value.

    ``keep_size`` is not accepted. Albumentations defaults it to ``True`` (the output keeps the input's height and
    width) and Kornia's ``RandomPerspective`` always behaves that way, so the default maps cleanly; ``keep_size=False``
    would change the output resolution, which this pipeline cannot express (see the note in
    :func:`build_kornia_pipeline` about size-preserving transforms), so it is refused rather than silently ignored.
    r   )ÚRandomPerspectiveÚ	keep_sizeFa   Perspective(keep_size=False) is not supported on the Kornia GPU backend: it changes the output resolution, but the GPU augmentation path requires a fixed batch height and width. Use keep_size=True (the Albumentations default), or run this augmentation on the CPU (albumentations) backend.c                ó   •— g | ]}|‰v ¯|‘Œ	S r<   r<   r„   s     €r   r‡   z%_make_perspective.<locals>.<listcomp>  s   ø€ ÐCÐCÐC�Q°q¸F°{°{ˆq°{°{°{r   z¡GPU augmentation (Kornia) Perspective ignores %s (Kornia's RandomPerspective exposes only distortion_scale and p). CPU augmentation (albumentations) honors them.rˆ   c              3  ó4   K  — | ]}t          |¦  «        V — Œd S rŠ   r‹   r�   s     r   rŽ   z$_make_perspective.<locals>.<genexpr>"  r�   r   rs   )gš™™™™™©?r™   r®   aF  GPU augmentation (Kornia) Perspective uses distortion_scale=%.3f sampled uniformly from [0, %.3f]. CPU augmentation (albumentations) samples each corner offset from abs(N(0, sigma)) over sigma in [%.3f, %.3f], so the GPU path distorts more on a typical sample. Use the albumentations backend if the exact distribution matters.rA   r]   r   )Údistortion_scaler]   )r_   rò   r`   rH   Ú_PERSPECTIVE_IGNORED_KEYSrQ   rS   rž   rD   rN   r   rJ   )rY   rò   rŸ   Ú	raw_scalers   s   `    r   Ú_make_perspectiverù   ý  s\  ø€ ð* 6Ð5Ð5Ð5Ð5Ð5à‡z‚z�+ÑÔ %Ð'Ð'Ýð(ñ
ô 
ð 	
ð DÐCÐCÐCÕ3ÐCÑCÔC€GØð 
Ý�Šð=ð �IŠIÐ/Ð/ wÐ/Ñ/Ô/Ñ/Ô/ñ		
ô 	
ð 	
ð —
’
˜7 KÑ0Ô0€IÝ'1°)½cÅ5¸\Ñ'JÔ'JÐdˆS•%˜	Ñ"Ô"Ð#Ð#ÕPYÐZcÑPdÔPd€EÝ
‡N‚Nð	Lð 	ˆaŒØˆaŒØˆaŒØˆaŒñ	ô 	ð 	ð ÐØ˜qœØ
�*Š*�S˜#Ñ
Ô
ðñ ô ð r   )ÚHorizontalFlipÚVerticalFlipÚRotateÚAffineÚShiftScaleRotateÚColorJitterÚToGrayÚRandomBrightnessContrastrÂ   Ú
GaussNoiserÐ   ÚSharpenÚEqualizeÚCLAHEÚPerspectivez*dict[str, Callable[[dict[str, Any]], Any]]Ú	_REGISTRYFÚ
aug_configúdict[str, dict[str, Any]]Ú
resolutionÚ
with_masksÚinclude_keypointsc           	     ó°  — t          ¦   «          ddlm} t          | |t          j        ¬¦  «        }t          |t          ¦  «        sJ ‚g }|                     ¦   «         D ]g\  }}t           
                    |¦  «        }	|	€(t          d|›dt          t          ¦  «        › d�¦  «        ‚|                      |	|¦  «        ¦  «         Œh|rg d¢nd	d
g}
 ||d|
iŽS )ak  Build a Kornia ``AugmentationSequential`` from an aug_config dict.

    Each key in *aug_config* is looked up in ``_REGISTRY`` and instantiated with the corresponding parameter dict.
    Unknown keys raise ``ValueError``.

    Args:
        aug_config: Mapping of augmentation names to parameter dicts, identical
            to the format accepted by the Albumentations path (e.g. ``{"HorizontalFlip": {"p": 0.5}}``).
        resolution: Target image resolution in pixels (currently reserved for
            future resolution-aware augmentations).
        with_masks: When ``True``, include ``"mask"`` in ``data_keys`` so
            auxiliary masks are augmented in sync with images and boxes. The training DataModule always enables this
            to transport its padding mask; segmentation batches concatenate instance-mask channels before the final
            padding channel. The pipeline then expects three inputs ``(img, boxes, masks)`` and returns three outputs.
            Defaults to ``False`` for direct detection-only callers.
        include_keypoints: When ``True``, keypoint-unsafe horizontal-flip
            transforms are dropped with a warning before the Kornia pipeline is built.

    Returns:
        A ``kornia.augmentation.AugmentationSequential`` instance.

    Raises:
        ValueError: If *aug_config* contains an unsupported augmentation key.

    Examples:
        >>> from rfdetr.datasets.aug_configs import AUG_CONSERVATIVE
        >>> pipeline = build_kornia_pipeline(AUG_CONSERVATIVE, resolution=560)
        >>> pipeline_seg = build_kornia_pipeline(AUG_CONSERVATIVE, resolution=560, with_masks=True)
    r   )ÚAugmentationSequential)r  ÚwarnNzUnknown augmentation key z) for Kornia GPU backend. Supported keys: ú.)ÚinputÚ	bbox_xyxyrà   r  r  Ú	data_keys)r0   r_   r  r	   rQ   rS   rD   rl   Úitemsr  r`   rH   ÚsortedÚappend)r  r
  r  r  r  Úfiltered_aug_configÚ
transformsr”   rY   Úfactoryr  s              r   r   r   Q  s$  € õF ÑÔÐØ:Ð:Ð:Ð:Ð:Ð:å=ØØ+ÝŒ^ðñ ô Ðõ
 Ð)­4Ñ0Ô0Ð0Ð0Ð0à€JØ+×1Ò1Ñ3Ô3ð +ð +‰ˆˆfÝ—-’- Ñ%Ô%ˆØˆ?ÝØq¨DÐqÐqÕ]cÕdmÑ]nÔ]nÐqÐqÐqñô ð ð 	×Ò˜'˜' &™/œ/Ñ*Ô*Ð*Ð*à2<ÐXÐ.Ð.Ð.Ð.À7ÈKÐBX€IØ!Ð!Ø	ðàðð ð r   Úmeanútuple[float, ...]rÌ   c                óD   — t          ¦   «          ddlm}  || |¬¦  «        S )aA  Build a Kornia ``Normalize`` transform for GPU-side normalization.

    Args:
        mean: Per-channel mean values.  Defaults to ImageNet statistics.
        std: Per-channel standard deviation values.  Defaults to ImageNet
            statistics.

    Returns:
        A ``kornia.augmentation.Normalize`` instance.
    r   )Ú	Normalize)r  rÌ   )r0   r_   r  )r  rÌ   r  s      r   Úbuild_normalizer  Ž  sA   € õ ÑÔÐØ-Ð-Ð-Ð-Ð-Ð-àˆ9ØØðñ ô ð r   Útargetsúlist[dict[str, Any]]Údeviceútorch.deviceútuple[Tensor, Tensor]c                ó€  — t          | ¦  «        dk    r:t          j        ddd|¬¦  «        t          j        ddt          j        |¬¦  «        fS d„ | D ¦   «         }|rt	          |¦  «        nd}t          | ¦  «        }|dk    r:t          j        |dd|¬¦  «        t          j        |dt          j        |¬¦  «        fS t          j        ||d|¬¦  «        }t          j        ||t          j        |¬¦  «        }t          | ¦  «        D ]6\  }}|d         j        d         }	|	dk    r|d         ||d|	…f<   d||d|	…f<   Œ7||fS )	u  Pack variable-length xyxy boxes into a padded tensor and valid mask.

    Kornia ``AugmentationSequential`` expects boxes as ``[B, N_max, 4]``. This function zero-pads each image's boxes to
    the maximum count in the batch and returns a boolean mask indicating which entries are real.

    Args:
        targets: List of target dicts (one per image), each containing a
            ``"boxes"`` key with an ``[N_i, 4]`` tensor in xyxy format.
        device: Device on which to allocate the output tensors.

    Returns:
        Tuple of:
            - ``boxes_padded`` â€” ``[B, N_max, 4]`` float tensor (zero-padded).
            - ``valid_mask``   â€” ``[B, N_max]`` bool tensor (``True`` = real box).

        When ``B == 0`` or all images have zero boxes, both tensors have ``N_max == 0``.
    r   é   )r!  ©Údtyper!  c                ó4   — g | ]}|d          j         d         ‘ŒS )Úboxesr   )Úshape)r…   Úts     r   r‡   z!collate_boxes.<locals>.<listcomp>Å  s$   € Ð7Ð7Ð7¨!�!�G”*Ô" 1Ô%Ð7Ð7Ð7r   r)  NT)rG   ÚtorchÚzerosr   rP   Ú	enumerater*  )
r  r!  Ú
box_countsÚn_maxÚ
batch_sizeÚboxes_paddedÚ
valid_maskÚir+  Úns
             r   Úcollate_boxesr6  ª  s_  € õ* ˆ7�|„|�qÒÐåŒK˜˜1˜a¨Ð/Ñ/Ô/ÝŒK˜˜1¥E¤J°vÐ>Ñ>Ô>ð
ð 	
ð
 8Ð7¨wÐ7Ñ7Ô7€JØ)Ð0�C�
‰OŒOˆO¨q€EÝ�W‘”€Jà�‚z€zåŒK˜
 A q°Ð8Ñ8Ô8ÝŒK˜
 A­U¬ZÀÐGÑGÔGð
ð 	
õ
 ”;˜z¨5°!¸FÐCÑCÔC€LÝ”˜Z¨µe´jÈÐPÑPÔP€Jå˜'Ñ"Ô"ð %ð %‰ˆˆ1ØˆgŒJÔ˜QÔˆØˆqŠ5ˆ5Ø"# G¤*ˆL˜˜B˜Q˜B˜ÑØ $ˆJ�q˜"˜1˜"�uÑøà˜Ð#Ð#r   r0  Úimage_heightÚimage_widthr   c                ó^  — t          | ¦  «        }t          j        ||||t          j        |¬¦  «        }t	          | ¦  «        D ]i\  }}d|vs|dk    rŒ|d                              t          j        |¬¦  «        }	t          |	j        d         |¦  «        }
|
dk    r|	d|
…         ||d|
…f<   Œj|S )uà  Pack variable-length instance masks into a zero-padded ``[B, N_max, H, W]`` tensor.

    Kornia ``AugmentationSequential`` expects masks as ``[B, N_max, H, W]`` when ``data_keys`` includes ``"mask"``.
    This function zero-pads each image's masks to *n_max* channels (matching the padding used by :func:`collate_boxes`)
    and converts boolean masks to ``float32`` for Kornia compatibility.

    Args:
        targets: List of target dicts (one per image).  Each dict may optionally
            contain a ``"masks"`` key with an ``[N_i, H, W]`` boolean tensor. Dicts without the key are treated as
            having zero instances.
        device: Device on which to allocate the output tensor.
        n_max: Maximum instance count across the batch â€” must equal
            ``collate_boxes(targets, device)[1].shape[1]`` to keep box/mask indices in sync.
        image_height: Spatial height ``H`` of each mask (pixels).
        image_width: Spatial width ``W`` of each mask (pixels).

    Returns:
        Float32 tensor of shape ``[B, N_max, H, W]``, zero-padded where ``N_i < N_max``.  Boolean input masks are cast
        to ``float32`` (``True â†’ 1.0``, ``False â†’ 0.0``).

    Examples:
        >>> import torch
        >>> targets = [{"masks": torch.ones(2, 8, 8, dtype=torch.bool)}]
        >>> out = collate_masks(targets, torch.device("cpu"), n_max=2, image_height=8, image_width=8)
        >>> out.shape
        torch.Size([1, 2, 8, 8])
        >>> out.dtype
        torch.float32
    r&  Úmasksr   N)rG   r,  r-  Úfloat32r.  ÚtoÚminr*  )r  r!  r0  r7  r8  r1  Úmasks_paddedr4  r+  Úmasks_ir5  s              r   Úcollate_masksr@  Û  s½   € õH �W‘”€JÝ”;˜z¨5°,ÀÕSXÔS`ÐioÐpÑpÔp€LÝ˜'Ñ"Ô"ð .ð .‰ˆˆ1Ø˜!ÐÐ˜u¨šz˜zØØ�G”*—-’-¥e¤m¸F�-ÑCÔCˆÝ�”˜aÔ  %Ñ(Ô(ˆØˆqŠ5ˆ5Ø")¨"¨1¨"¤+ˆL˜˜B˜Q˜B˜ÑøØÐr   Ú	boxes_augÚvalidÚ	masks_augúTensor | Nonec                óÎ  — |�U|j         dd…         |j         k    s=J dt          |j         dd…         ¦  «        › dt          |j         ¦  «        › d�¦   «         ‚g }t          |¦  «        D �]ú\  }}|                     ¦   «         }|d         j         d         }	|	dk    s|j         d         dk    r|                     |¦  «         ŒZ||d|	…f         }
| |d|	…f         }|                     ¦   «         }|dd…df                              d|¬	¦  «         |dd…df                              d|¬	¦  «         |dd…df                              d|¬	¦  «         |dd…d
f                              d|¬	¦  «         |dd…df         |dd…df         z
  }|dd…d
f         |dd…df         z
  }|
|dk    z  |dk    z  }||         |d<   d|v r|d         |         |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<   d|v r|d         |         |d<   |� ||d|	…f         }||         t          k    |d<   |                     |¦  «         �Œü|S )ue  Unpack augmented boxes (and optionally masks), clamp to image bounds, remove zero-area boxes.

    After Kornia augmentation the padded ``[B, N_max, 4]`` tensor is unpacked back into per-image target dicts.  Boxes
    are clamped to ``[0, W] x [0, H]`` and any that collapse to zero area are removed along with their corresponding
    ``labels``, ``area``, ``iscrowd``, and (if provided) ``masks`` entries.

    Args:
        boxes_aug: Augmented boxes tensor ``[B, N_max, 4]`` in xyxy format.
        valid: Boolean mask ``[B, N_max]`` from :func:`collate_boxes`.
        targets: Original target dicts; each dict is shallow-copied before
            modification â€” the input list itself is not mutated.
        image_height: Image height in pixels (for clamping).
        image_width: Image width in pixels (for clamping).
        masks_aug: Optional augmented masks tensor ``[B, N_max, H, W]``
            (float32) from Kornia.  When provided, masks are filtered by the same ``keep`` mask as boxes, thresholded at
            ``> 0.5`` to bool, and stored under ``"masks"`` in each output target dict.  When ``None``, any existing
            ``"masks"`` entry in the target dict is preserved unchanged.

    Returns:
        A new list of target dicts with updated ``boxes``, ``labels``, ``area``, ``iscrowd``, and (when *masks_aug* is
        given) ``masks`` entries.
    NrB   zmasks_aug batch/n_max dims z must match valid shape zM; ensure collate_masks is called with n_max=valid.shape[1] from collate_boxesr)  r   rA   )r=  rP   r   ÚlabelsÚareaÚiscrowdr:  )r*  rF   r.  Úcopyr  ÚcloneÚclamp_r   )rA  rB  r  r7  r8  rC  Únew_targetsr4  r+  Ún_origÚvÚboxes_iÚwidthsÚheightsÚkeepÚ
kept_boxesr?  s                    r   Úunpack_boxesrT    s÷  € ð< ÐØŒ˜r ˜rÔ" e¤kÒ1Ð1Ð1ð6­%°	´ÀÀÀÔ0CÑ*DÔ*Dð 6ð 6Ý  ¤Ñ-Ô-ð6ð 6ð 6ñ 2Ô1Ð1ð
 )+€KÝ˜'Ñ"Ô"ð (ñ (‰ˆˆ1Ø�FŠF‰HŒHˆØ�7”Ô! !Ô$ˆà�QŠ;ˆ;˜%œ+ aœ.¨AÒ-Ð-Ø×Ò˜qÑ!Ô!Ð!Øð �!�W�f�W�*ÔˆØ˜A˜w ˜w˜JÔ'ˆð —-’-‘/”/ˆØ����1�Œ×Ò ¨ÐÑ4Ô4Ð4Ø����1�Œ×Ò ¨ÐÑ5Ô5Ð5Ø����1�Œ×Ò ¨ÐÑ4Ô4Ð4Ø����1�Œ×Ò ¨ÐÑ5Ô5Ð5ð ˜˜˜˜A˜” ¨¨¨¨A¨¤Ñ.ˆØ˜!˜!˜!˜Q˜$”- '¨!¨!¨!¨Q¨$¤-Ñ/ˆØ�F˜Q’JÑ 7¨Q¢;Ñ/ˆà˜T”]ˆˆ'‰
Ø�qˆ=ˆ=Ø˜Hœ+ dÔ+ˆAˆh‰KØ�Qˆ;ˆ;à˜7œˆJØ# A A A q DÔ)¨J°q°q°q¸!°tÔ,<Ñ<ÀÈAÈAÈAÈqÈDÔAQÐT^Ð_`Ð_`Ð_`ÐbcÐ_cÔTdÑAdÑeˆAˆf‰IØ˜ˆ>ˆ>Ø˜Yœ<¨Ô-ˆAˆi‰LØÐ Ø  7 F 7 
Ô+ˆGØ  œÕ)AÒAˆAˆg‰Jð
 	×Ò˜1ÑÔÐÑàÐr   )r   r   )r!   r   r    r"   r   r   )r*   r   r    r   r   r+   )r3   r   r   r   )r*   r6   r    r"   r   r   )r   r+   )r>   r   r   r?   rŠ   )r>   r   rK   r   rL   rM   r   rN   )rY   rZ   r   r   )FF)
r  r	  r
  rN   r  r   r  r   r   r   )r  r  rÌ   r  r   r   )r  r   r!  r"  r   r#  )r  r   r!  r"  r0  rN   r7  rN   r8  rN   r   r   )rA  r   rB  r   r  r   r7  rN   r8  rN   rC  rD  r   r   )9Ú__doc__Ú
__future__r   Úcollections.abcr   Útypingr   r   r,  r   r   r   Úrfdetr.datasets._aug_utilsr	   Úrfdetr.utilities.loggerr
   rQ   Ú__doctest_requires__ÚIMAGENET_MEANÚIMAGENET_STDr   Ú__annotations__r   r   r)   r2   r5   r8   r0   r'   rJ   rX   ra   rd   rn   rz   r�   rw   r©   r´   r¹   r¾   rÈ   rÍ   rÑ   rÙ   râ   rä   rï   r÷   rù   r  r   r  r6  r@  rT  r<   r   r   ú<module>r_     s8  ðð!ð !ð !ðF #Ð "Ð "Ð "Ð "Ð "à $Ð $Ð $Ð $Ð $Ð $Ø Ð Ð Ð Ð Ð Ð Ð à €€€Ø Ð Ð Ð Ð Ð à -Ð -Ð -Ð -Ð -Ð -Ø JÐ JÐ JÐ JÐ JÐ JØ .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€à/°(°Ð<Ð ð &€à$€ð
 7=Ð "Ð <Ð <Ð <Ñ <ð #&Ð Ð %Ð %Ð %Ñ %ð*ð *ð *ð *ð$ KOð 3Dð 3Dð 3Dð 3Dð 3Dð 3Dðlð ð ð ð:2ð 2ð 2ð 2ð> !ð)Nð )Nð )Nð )Nð )Nð )NðXkð kð kð kð	
ð 	
ð 	
ð 	
ð"(ð (ð (ð (ð>6ð 6ð 6ð 6ð 6ðr8ð 8ð 8ð 8ð6ð 6ð 6ð 6ðð ð ð ð*$ð $ð $ð $ðP$Ð  ð)ð )ð )ð )ð@ð @ð @ð @ðFð ð ð ð"3ð 3ð 3ð 3ð$ð ð ð ðð ð ð ðBð ð ð ð8Oð Oð Oð Oð&ð ð ð ð:2ð 2ð 2ð 2ð""ð "ð "ð "ðJð ð ð ð*Ð ð9ð 9ð 9ð 9ðz ,Ø'ØØØ0Ø%ØØ @Ø'Ø#ØØØØØ$ð9ð 9€	ð ð ð ñ ð6 Ø#ð	:ð :ð :ð :ð :ð| ,Ø)ðð ð ð ð ð8.$ð .$ð .$ð .$ðb-ð -ð -ð -ðl  $ðOð Oð Oð Oð Oð Oð Or   