§
    ­¸jC  ã                  ó¬  — U d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	m
Z
mZ 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mZ dd	lmZmZ dd
lmZmZ ddlmZmZmZmZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(m)Z) ddl*m+Z+m,Z, ddl-m.Z.  e.¦   «         Z/dZ0dnd„Z1 e2h d£¦  «        Z3de4d<   dod„Z5dpd„Z6dqd!„Z7	 drdsd&„Z8dtd*„Z9dud.„Z:dvd2„Z;	 	 	 dwdxd;„Z<d3d3d4d5d3d3d<œdydA„Z=dzdF„Z>d{dH„Z?d|dN„Z@ G dO„ dPejA        jB        ¦  «        ZB G dQ„ dR¦  «        ZCddSdTœd}dX„ZDddSdTœd~d\„ZEdSd]œddd„ZFdSd]œdde„ZGdSd]œddf„ZH	 	 	 	 	 	 	 	 	 d€d�di„ZI	 	 	 	 	 	 	 	 	 d€d�dj„ZJd‚dl„ZKd‚dm„ZLdS )ƒzžCOCO dataset which returns image_id for evaluation.

Mostly copy-paste from https://github.com/pytorch/vision/blob/13b35ff/references/detection/coco_utils.py
é    )ÚannotationsN)ÚPath)ÚAnyÚDictÚListÚOptionalÚcast)ÚImage)ÚTensor)ÚToDtypeÚToImage)ÚAugmentationBackendÚ
MultiScale)Ú_warn_keypoint_hflip_disabledÚresolve_keypoint_flip_pairs)ÚComposeÚRandomChoiceÚRandomHorizontalFlipÚRandomResizeÚRandomSelectÚRandomSizedCropÚResize)Ú
AUG_CONFIG)Údecode_image)Úis_gpu_postprocessÚresolve_backend_for_build)ÚAlbumentationsWrapperÚ	Normalize)Ú
get_loggeri5  Údataset_dirÚstrÚreturnÚboolc                óP   — t          | ¦  «        dz  dz                       ¦   «         S )NÚtrainú_annotations.coco.json)r   Úexists)r    s    úd/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/datasets/coco.pyÚis_valid_coco_datasetr)   7   s'   € Ý�ÑÔ Ñ'Ð*BÑB×JÒJÑLÔLÐLó    >   NÚ ÚnoneÚnullzfrozenset[str | None]Ú_SUPERCATEGORY_PLACEHOLDERSÚ	coco_dataúdict[str, Any]úset[int]c                óB   — d„ |                       dg ¦  «        D ¦   «         S )aÀ  Collect the category ids referenced by at least one annotation of a parsed COCO file.

    Args:
        coco_data: Parsed COCO JSON. A missing ``annotations`` key yields an empty set.

    Returns:
        Category ids carrying at least one annotation.

    Examples:
        >>> annotated_category_ids({"annotations": [{"category_id": 3}, {"category_id": 3}]})
        {3}
        >>> annotated_category_ids({"categories": []})
        set()
    c                ó8   — h | ]}t          |d          ¦  «        ’ŒS ©Úcategory_id©Úint©Ú.0Ú
annotations     r(   ú	<setcomp>z)annotated_category_ids.<locals>.<setcomp>N   s%   € Ð^Ð^Ð^¨z�C�
˜=Ô)Ñ*Ô*Ð^Ð^Ð^r*   r   ©Úget)r/   s    r(   Úannotated_category_idsr>   ?   s(   € ð _Ð^¸Y¿]º]È=ÐZ\Ñ=]Ô=]Ð^Ñ^Ô^Ð^r*   Úcategoryc                ó¦   — 	 t          t          | d         ¦  «        S # t          $ r) t          d|                      dd¦  «        › d�¦  «        d‚w xY w)zZReturn a category's ``name``, failing with an actionable message when the field is absent.ÚnamezCOCO category ÚidÚ?zg is missing the required 'name' field; every entry of the 'categories' list needs an 'id' and a 'name'.N)r	   r!   ÚKeyErrorr=   ©r?   s    r(   Ú_category_namerF   Q   sv   € ðÝ•C˜ &Ô)Ñ*Ô*Ð*øÝð ð ð ÝðO˜XŸ\š\¨$°Ñ4Ô4ð Oð Oð Oñ
ô 
ð ð	ðøøøs	   ‚ �3Aú
int | Nonec                ój   — 	 t          | d         ¦  «        S # t          t          t          f$ r Y dS w xY w)z\Return a category's ``id`` coerced to ``int``, or ``None`` when it is absent or not numeric.rB   N)r7   rD   Ú	TypeErrorÚ
ValueErrorrE   s    r(   Ú_normalized_category_idrK   \   sB   € ðÝ�8˜D”>Ñ"Ô"Ð"øÝ•i¥Ð,ð ð ð Øˆtˆtðøøøs   ‚ —2±2Ú
categoriesúlist[dict[str, Any]]Úannotated_idsúset[int] | Nonec                ó¼   ‡‡— t          | d„ ¬¦  «        }d„ |D ¦   «         }d„ |D ¦   «         Š‰s|S d„ |pt          ¦   «         D ¦   «         Šˆˆfd„|D ¦   «         }|p|S )u¾
  Drop unannotated grouping nodes from a COCO ``categories`` list.

    Roboflow COCO exports prepend a synthetic root category (``supercategory: "none"``) whose name is reused as the
    ``supercategory`` of every real class. It carries no annotations, yet it consumes a model output slot once the
    category list is turned into contiguous label indices. Removing it keeps class names, class count and label
    remapping in agreement (GitHub #609).

    A category is dropped when it is named as another category's ``supercategory`` **and** no annotation references its
    id. A category whose own ``supercategory`` equals its own ``name`` â€” the COCO convention for a top-level class such
    as ``{"name": "person", "supercategory": "person"}`` â€” is not a parent of itself and is therefore kept; the same
    name still counts as a parent when a *different* category groups under it. The annotation guard keeps genuinely
    labelled parents of hierarchical datasets, and is applied per category by its own ``id`` â€” categories sharing a
    ``name`` are judged independently, so an annotated leaf is never dropped alongside a same-named grouping node. Ids
    are coerced to ``int`` before that lookup, so exports shipping string ids still match ``annotated_ids``. Flat
    datasets â€” every ``supercategory`` a placeholder â€” are returned untouched, as is any input where filtering would
    remove everything.

    Args:
        categories: Raw COCO ``categories`` entries; each needs an ``id`` and a ``name``.
        annotated_ids: Category ids carrying at least one annotation, typically from
            :func:`annotated_category_ids`. ``None`` treats every category as unannotated, which is the right default
            when only the category list is available.

    Returns:
        The kept categories, sorted by ``id``.

    Examples:
        >>> categories = [
        ...     {"id": 0, "name": "eggmasses", "supercategory": "none"},
        ...     {"id": 1, "name": "stake", "supercategory": "eggmasses"},
        ...     {"id": 2, "name": "tree", "supercategory": "eggmasses"},
        ... ]
        >>> [category["name"] for category in filter_parent_categories(categories, {1, 2})]
        ['stake', 'tree']
        >>> [category["name"] for category in filter_parent_categories(categories, {0, 1, 2})]
        ['eggmasses', 'stake', 'tree']
        >>> self_parented = [
        ...     {"id": 1, "name": "person", "supercategory": "person"},
        ...     {"id": 2, "name": "vehicle", "supercategory": "none"},
        ...     {"id": 3, "name": "car", "supercategory": "vehicle"},
        ... ]
        >>> [category["name"] for category in filter_parent_categories(self_parented, {3})]
        ['person', 'car']
    c                óF   — t          | ¦  «        d u t          | ¦  «        pdfS )Nr   )rK   rE   s    r(   ú<lambda>z*filter_parent_categories.<locals>.<lambda>–   s)   € Ý# HÑ-Ô-°Ð5Ý# HÑ-Ô-Ð2°ð
€ r*   )Úkeyc                ód   — g | ]-}|                      d d¦  «        |                      d¦  «        f‘Œ.S )Úsupercategoryr,   rA   r<   )r9   r?   s     r(   ú
<listcomp>z,filter_parent_categories.<locals>.<listcomp>›   s8   € ÐmÐmÐmÐYa˜Ÿš _°fÑ=Ô=¸x¿|º|ÈFÑ?SÔ?SÐTÐmÐmÐmr*   c                ó6   — h | ]\  }}|t           v¯||k    ¯|’ŒS © )r.   )r9   rU   rA   s      r(   r;   z+filter_parent_categories.<locals>.<setcomp>œ   s=   € ð ð ð áˆM˜4ØÕ ;Ð;Ð;ÀÐQUÒ@UÐ@Uð 	à@UÐ@UÐ@Ur*   c                ód   — h | ]-}t          |t          t          f¦  «        ¯t          |¦  «        ’Œ.S rX   )Ú
isinstancer7   r!   )r9   r5   s     r(   r;   z+filter_parent_categories.<locals>.<setcomp>¤   s8   € ÐuÐuÐu kÕQ[Ð\gÕjmÕorÐisÑQtÔQtÐu•�[Ñ!Ô!ÐuÐuÐur*   c                óX   •— g | ]&}t          |¦  «        ‰v rt          |¦  «        ‰v°$|‘Œ'S rX   )rF   rK   )r9   r?   Ú	annotatedÚparentss     €€r(   rV   z,filter_parent_categories.<locals>.<listcomp>¥   sK   ø€ ð ð ð àÝ˜xÑ(Ô(¨GÐ3Ð3Õ8OÐPXÑ8YÔ8YÐajÐ8jÐ8jð 	à8jÐ8jÐ8jr*   )ÚsortedÚset)rL   rN   ÚorderedÚsupercategoriesÚkeptr\   r]   s        @@r(   Úfilter_parent_categoriesrc   d   sÁ   øø€ õ` Øð
ð 
ðñ ô €Gð nÐmÐelÐmÑmÔm€Oðð à#2ðñ ô €Gð
 ð ØˆàuÐu°mÐ6LÅsÁuÄuÐuÑuÔu€Iðð ð ð ð àðñ ô €Dð ˆ?�7Ðr*   Údataset_rootr   údict[int, int] | Nonec                óÀ  — | dz  dz  }|                      ¦   «         sdS 	 t          |d¬¦  «        5 }t          j        |¦  «        }ddd¦  «         n# 1 swxY w Y   t	          |d         t          |¦  «        ¦  «        }d„ t          |¦  «        D ¦   «         S # t          t          t          t          f$ r'}t                               d||¦  «         Y d}~dS d}~ww xY w)	u˜  Derive the train split's ``category_id`` â†’ label-index mapping so the other splits can reuse it.

    Label indices are positions in the filtered category list, so a grouping category annotated in one split but not
    in another would receive a different index per split â€” silently shifting every later label of the smaller split.
    Deriving the mapping once from ``train`` â€” the split :meth:`RFDETR._detect_num_classes_for_training` and
    :meth:`RFDETR._load_classes` already read â€” keeps validation and test targets aligned with the label space the
    model is trained on.

    Args:
        dataset_root: Roboflow dataset root holding the ``train``/``valid``/``test`` split directories.

    Returns:
        Mapping from COCO category id to contiguous label index, or ``None`` when the train annotation file is missing
        or unreadable, in which case the caller keeps the split-local mapping.
    r%   r&   Nzutf-8)ÚencodingrL   c                ó@   — i | ]\  }}t          |d          ¦  «        |“ŒS ©rB   r6   ©r9   Úlabelr?   s      r(   ú
<dictcomp>z*_train_split_cat2label.<locals>.<dictcomp>Å   s*   € ÐRÐRÐR©¨u°h•�H˜T”NÑ#Ô# UÐRÐRÐRr*   z¡Could not derive the train-split label mapping from %s (%s); falling back to this split's own mapping. Its label indices may diverge from the ones training used.)r'   ÚopenÚjsonÚloadrc   r>   Ú	enumerateÚOSErrorrJ   rD   rI   ÚloggerÚwarning)rd   Útrain_ann_fileÚfileÚtrain_annotationsrb   Úexcs         r(   Ú_train_split_cat2labelrx   ®   s7  € ð  " GÑ+Ð.FÑF€NØ× Ò Ñ"Ô"ð ØˆtðÝ�.¨7Ð3Ñ3Ô3ð 	0°tÝ $¤	¨$¡¤Ðð	0ð 	0ð 	0ñ 	0ô 	0ð 	0ð 	0ð 	0ð 	0ð 	0ð 	0øøøð 	0ð 	0ð 	0ð 	0å'Ð(9¸,Ô(GÕI_Ð`qÑIrÔIrÑsÔsˆØRÐRÅ)ÈDÁ/Ä/ÐRÑRÔRÐRøÝ•Z¥­9Ð5ð ð ð Ý�ŠðIàØñ		
ô 	
ð 	
ð ˆtˆtˆtˆtˆtøøøøðøøøs:    B ±AÁB ÁAÁB ÁAÁ>B ÂCÂ6CÃCÚcocor   ú	list[int]c                óˆ  — d„ | j                              ¦   «         D ¦   «         }|rt          |¦  «        S | j                             ¦   «         D ]f}|                     d¦  «        s't          |                     dd¦  «        ¦  «        dk    r(|                     t          |d         ¦  «        ¦  «         Œgt          |¦  «        S )zLReturn sorted COCO category ids that carry keypoint metadata or annotations.c                ó†   — h | ]>\  }}|                      d ¦  «        s|                      d¦  «        ¯/t          |¦  «        ’Œ?S )Ú	keypointsÚskeleton)r=   r7   )r9   Úcat_idr?   s      r(   r;   z/_category_ids_with_keypoints.<locals>.<setcomp>Ò   sZ   € ð ð ð Ù(˜ ÀÇÂÈkÑAZÔAZðØ^f×^jÒ^jÐkuÑ^vÔ^vðÝˆF‰Œðð ð r*   r}   Únum_keypointsr   r5   )ÚcatsÚitemsr^   ÚannsÚvaluesr=   r7   Úadd)ry   Úcategory_idsr:   s      r(   Ú_category_ids_with_keypointsr‡   Ð   sÆ   € ðð Ø,0¬I¯OªOÑ,=Ô,=ðñ ô €Lð ð $Ý�lÑ#Ô#Ð#à”i×&Ò&Ñ(Ô(ð =ð =ˆ
Ø�>Š>˜+Ñ&Ô&ð 	=­#¨j¯nªn¸_ÈaÑ.PÔ.PÑ*QÔ*QÐTUÒ*UÐ*UØ×Ò�S ¨MÔ!:Ñ;Ô;Ñ<Ô<Ð<øÝ�,ÑÔÐr*   Únum_keypoints_per_classúlist[int] | Noneúdict[int, int]c                ó”  ‡— t          |pg ¦  «        }d„ t          |¦  «        D ¦   «         }|st          d¦  «        ‚t          | ¦  «        }|st          d¦  «        ‚t	          |¦  «        t	          |¦  «        k    r0t          dt	          |¦  «        › dt	          |¦  «        › d�¦  «        ‚t          d„ | j                             ¦   «         D ¦   «         ¦  «        }t          t	          |¦  «        t          |¦  «        dz   ¦  «        }t          ¦   «         Ši }t          ||¦  «        D ]K\  }}	|	|k    r&t          d	|	› d
|› dt	          |¦  «        › d�¦  «        ‚|	||<   ‰                     |	¦  «         ŒLˆfd„t          |¦  «        D ¦   «         }
|D ]4}||v rŒ|
st          d|› d�¦  «        ‚|
                     d¦  «        ||<   Œ5|S )aÂ  Map COCO category ids onto model label slots that have keypoint capacity.

    RF-DETR keypoint schemas are indexed by model label. The preview person-keypoint schema is ``[17]``: label slot
    ``0`` owns the 17 COCO person keypoints. Legacy checkpoints may still use a background-first ``[0, 17]`` schema
    where slot ``0`` is reserved (0 keypoints) and slot ``1`` is person. This helper maps keypoint-bearing categories
    onto slots with a non-zero keypoint count (``count > 0``), so both layouts keep supervision aligned. For multi-class
    keypoint training supply e.g. ``[17, 4]`` where each non-zero entry corresponds to a keypoint-bearing category in
    ascending COCO category ID order.
    c                ó$   — g | ]\  }}|d k    ¯|‘ŒS )r   rX   )r9   ÚidxÚcounts      r(   rV   z-_build_keypoint_cat2label.<locals>.<listcomp>é   s!   € ÐIÐIÐI™J˜C ¸uÀqºy¸y�C¸y¸y¸yr*   z˜Keypoint COCO dataset requested, but num_keypoints_per_class has no active keypoint slots. Provide a schema such as [17] for the keypoint preview model.z·Keypoint COCO dataset has no keypoint category metadata and no keypoint annotations. Expected COCO categories with a 'keypoints' field or annotations with 'keypoints'/'num_keypoints'.z<Keypoint COCO dataset has more keypoint-bearing categories (z) than active schema slots (zR). Multi-class keypoint training needs an explicit num_keypoints_per_class schema.c              3  ó4   K  — | ]}t          |¦  «        V — Œd S ©Nr6   )r9   r   s     r(   ú	<genexpr>z,_build_keypoint_cat2label.<locals>.<genexpr>ý   s(   è è € ÐGÐG¨F�C ™KœKÐGÐGÐGÐGÐGÐGr*   é   zKeypoint schema slot z for category_id z# exceeds the detected class count (zE). Pass num_classes large enough to include this keypoint label slot.c                ó   •— g | ]}|‰v¯|‘Œ	S rX   rX   )r9   ÚslotÚassigned_slotss     €r(   rV   z-_build_keypoint_cat2label.<locals>.<listcomp>  s#   ø€ ÐWÐWÐW˜4¸DÈÐ<VÐ<V�$Ð<VÐ<VÐ<Vr*   z>No free model label slots remain for non-keypoint category_id ú.r   )Úlistrp   rJ   r‡   Úlenr^   r�   ÚkeysÚmaxr_   Úzipr…   ÚrangeÚpop)ry   rˆ   ÚschemaÚactive_slotsÚkeypoint_cat_idsÚsorted_cat_idsÚrequired_slotsÚ	cat2labelr   r”   Ú
free_slotsr•   s              @r(   Ú_build_keypoint_cat2labelr¥   Þ   sh  ø€ õ Ð)Ð/¨RÑ0Ô0€FØIÐI­)°FÑ*;Ô*;ÐIÑIÔI€LØð 
ÝðLñ
ô 
ð 	
õ
 4°DÑ9Ô9ÐØð 
Ýðqñ
ô 
ð 	
õ ÐÑÔ�s <Ñ0Ô0Ò0Ð0Ýð^ÝÐ$Ñ%Ô%ð^ð ^ÝCFÀ|ÑCTÔCTð^ð ^ð ^ñ
ô 
ð 	
õ ÐGÐG°d´i·n²nÑ6FÔ6FÐGÑGÔGÑGÔG€NÝ�˜^Ñ,Ô,­c°,Ñ.?Ô.?À!Ñ.CÑDÔD€NÝ"™uœu€NØ "€IåÐ,¨lÑ;Ô;ð !ð !‰ˆ�Ø�>Ò!Ð!Ýðo¨ð oð o¸vð oð oÝ˜Ñ'Ô'ðoð oð oñô ð ð !ˆ	�&ÑØ×Ò˜4Ñ Ô Ð Ð àWÐWÐWÐW¥5¨Ñ#8Ô#8ÐWÑWÔW€JØ ð .ð .ˆØ�YÐÐØØð 	iÝÐgÐ^dÐgÐgÐgÑhÔhÐhØ&ŸNšN¨1Ñ-Ô-ˆ	�&ÑÐàÐr*   Fé   é   Ú
resolutionr7   Úexpanded_scalesÚ
patch_sizeÚnum_windowsc                óˆ   ‡‡‡— | ‰‰z  z  Š|sg d¢ng d¢}ˆfd„|D ¦   «         }ˆˆfd„|D ¦   «         }ˆˆfd„|D ¦   «         }|S )N)éýÿÿÿéþÿÿÿéÿÿÿÿr   r’   é   é   r§   )éûÿÿÿéüÿÿÿr­   r®   r¯   r   r’   r°   r±   r§   é   c                ó   •— g | ]}‰|z   ‘ŒS rX   rX   )r9   ÚoffsetÚbase_num_patches_per_windows     €r(   rV   z.compute_multi_scale_scales.<locals>.<listcomp>  s   ø€ ÐIÐIÐI°vÐ)¨FÑ2ÐIÐIÐIr*   c                ó    •— g | ]
}|‰z  ‰z  ‘ŒS rX   rX   ©r9   Úscaler«   rª   s     €€r(   rV   z.compute_multi_scale_scales.<locals>.<listcomp>   s#   ø€ ÐLÐLÐL¸E�u˜zÑ)¨KÑ7ÐLÐLÐLr*   c                ó,   •— g | ]}|‰‰z  d z  k    ¯|‘ŒS )r°   rX   r¹   s     €€r(   rV   z.compute_multi_scale_scales.<locals>.<listcomp>!  s5   ø€ ð ð ð Ø¨e°zÀKÑ7OÐRSÑ7SÒ.SÐ.SˆÐ.SÐ.SÐ.Sr*   rX   )r¨   r©   rª   r«   ÚoffsetsÚscalesÚproposed_scalesr·   s     ``   @r(   Úcompute_multi_scale_scalesr¿     sž   øøø€ ð #-°¸kÑ1IÑ"JÐØ1@ÐlÐ)Ð)Ð)Ð)ÐFlÐFlÐFl€GØIÐIÐIÐIÀÐIÑIÔI€FØLÐLÐLÐLÐLÀVÐLÑLÔL€Oðð ð ð ð Ø*ðñ ô €Oð Ðr*   ©Úmulti_scaler©   rª   r«   Úscale_jitterÚinclude_masksÚ	image_setrÁ   rÂ   rÃ   c               ó„   — | dk    s|rdS |rt          t          ||||¦  «        ¦  «        n|}|rt          |d¦  «        n|S )a¦  Return the source extent below which the transform pipeline starts losing detail.

    :meth:`CocoDetection._decode_image` passes this to ``PIL.Image.draft`` so JPEG sources far larger than the training
    resolution are decoded at a reduced DCT scale instead of at full size. ``draft`` never returns an image smaller
    than the requested box, so the box preserves the largest direct-resize target. Scale jitter also preserves its
    600-pixel pre-crop resize floor, avoiding an extra upsample after JPEG decoding.

    Two cases return ``None`` (decode at full resolution):

    * Non-train splits.  :class:`~rfdetr.datasets.coco_eval.CocoEvaluator` scores predictions against the unscaled
      annotation file, so a reduced decode would shift ``orig_size`` and mis-scale every prediction.
    * Mask datasets.  RLE ``segmentation`` cannot be rescaled by :func:`scale_coco_annotation`.

    Args:
        image_set: Dataset split name.  Only ``"train"`` is decoded at a reduced scale.
        resolution: Base square resolution the split is built for.
        multi_scale: Whether multi-scale training is enabled.
        expanded_scales: Whether the multi-scale range is widened.
        patch_size: Patch size used to derive multi-scale candidates.
        num_windows: Window count used to derive multi-scale candidates.
        scale_jitter: Whether the training crop branch can resize the short side to 600 pixels.
        include_masks: Whether the dataset decodes segmentation masks.

    Returns:
        Minimum extent, in pixels, that a decoded image must retain on both axes, or ``None`` to decode at full size.

    Examples:
        >>> draft_size_for_transforms("val", 512) is None
        True
        >>> draft_size_for_transforms("train", 512, include_masks=True) is None
        True
        >>> draft_size_for_transforms("train", 512)
        512
        >>> draft_size_for_transforms("train", 512, multi_scale=True)
        768
    r%   NéX  )rš   r¿   )	rÄ   r¨   rÁ   r©   rª   r«   rÂ   rÃ   Údirect_branch_sizes	            r(   Údraft_size_for_transformsrÈ   '  sg   € ð^ �GÒÐ˜}ÐØˆtð ð	�Õ& z°?ÀJÐP[Ñ\Ô\Ñ]Ô]Ð]àð ð
 ,8ÐO�3Ð! 3Ñ'Ô'Ð'Ð=OÐOr*   r:   Úx_scaleÚfloatÚy_scalec                óz  ‡‡— t          | ¦  «        }d|v r"|d         \  }}}}|‰z  |‰z  |‰z  |‰z  g|d<   d|v r|d         ‰z  ‰z  |d<   |                     d¦  «        }|r!t          |¦  «        sˆˆfd„|D ¦   «         |d<   |                     d¦  «        }	|	rˆˆfd„t          |	¦  «        D ¦   «         |d<   |S )a¤  Return a COCO annotation scaled into its decoded image coordinate space.

    Needed when an image is decoded at a reduced scale (see :meth:`CocoDetection._decode_image`): ``ConvertCoco`` clamps
    boxes to the decoded image size, so annotations must move into the decoded image's coordinate space first. JPEG
    draft dimensions round each axis independently, so boxes, polygon points, keypoints, and area use separate x/y
    factors.
    Keypoint visibility, ``iscrowd``, and every other field are copied unchanged. RLE ``segmentation`` cannot be scaled
    this way, which is why :func:`draft_size_for_transforms` refuses to draft mask datasets.

    Args:
        annotation: One COCO annotation dict.  Not mutated.
        x_scale: Horizontal decoded-to-source ratio.
        y_scale: Vertical decoded-to-source ratio.

    Returns:
        Scaled copy of the annotation.

    Examples:
        >>> scale_coco_annotation({"bbox": [10, 20, 30, 40], "area": 1200, "category_id": 1}, 0.5, 0.25)
        {'bbox': [5.0, 5.0, 15.0, 10.0], 'area': 150.0, 'category_id': 1}
        >>> scale_coco_annotation({"keypoints": [10, 20, 2]}, 0.5, 0.25)
        {'keypoints': [5.0, 5.0, 2]}
    ÚbboxÚareaÚsegmentationc                óH   •— g | ]}ˆˆfd „t          |¦  «        D ¦   «         ‘ŒS )c                ó6   •— g | ]\  }}||d z  dk    r‰n‰z  ‘ŒS )r°   r   rX   ©r9   ÚindexÚvaluerÉ   rË   s      €€r(   rV   z4scale_coco_annotation.<locals>.<listcomp>.<listcomp>�  s2   ø€ ÐeÐeÐeÁ,À%ÈˆU ¨¡¨a¢ �g�g°WÑ=ÐeÐeÐer*   )rp   )r9   ÚpolygonrÉ   rË   s     €€r(   rV   z)scale_coco_annotation.<locals>.<listcomp>€  sK   ø€ ð "
ð "
ð "
àð fÐeÐeÐeÐeÕR[Ð\cÑRdÔRdÐeÑeÔeð"
ð "
ð "
r*   r}   c                óL   •— g | ] \  }}|d z  dk    r|n||d z  dk    r‰n‰z  ‘Œ!S )r±   r°   r   rX   rÒ   s      €€r(   rV   z)scale_coco_annotation.<locals>.<listcomp>†  sS   ø€ ð 
ð 
ð 
á��uð ˜Q‘Y !’^�^ˆEˆE¨¸UÀQ¹YÈ!º^¸^°'°'ÐQXÑ)Yð
ð 
ð 
r*   )Údictr=   Ú_is_rlerp   )
r:   rÉ   rË   ÚscaledÚxÚyÚwidthÚheightrÏ   r}   s
    ``       r(   Úscale_coco_annotationrÞ   `  s+  øø€ õ0 �*ÑÔ€FØ�ÐÐØ$ VœnÑˆˆ1ˆe�VØ˜g™+ q¨7¡{°E¸G±OÀVÈgÑEUÐVˆˆv‰Ø�ÐÐØ œ¨'Ñ1°GÑ;ˆˆv‰Ø—:’:˜nÑ-Ô-€LØð 
�G LÑ1Ô1ð 
ð"
ð "
ð "
ð "
ð "
à'ð"
ñ "
ô "
ˆˆ~Ñð —
’
˜;Ñ'Ô'€IØð 
ð
ð 
ð 
ð 
ð 
å )¨)Ñ 4Ô 4ð
ñ 
ô 
ˆˆ{Ñð €Mr*   rÏ   c                ó<   — t          | t          ¦  «        od| v od| v S )u:  Check whether a COCO segmentation entry is in RLE format.

    RLE annotations are dicts with ``"counts"`` and ``"size"`` keys, as opposed to polygon annotations which are lists
    of coordinate arrays. This is a structural check only â€” it verifies key presence but does not validate value types.
    A dict with counts=None will pass this check but fail downstream in convert_coco_poly_to_mask.

    Args:
        segmentation: A single COCO segmentation annotation entry.

    Returns:
        ``True`` if the entry looks like an RLE dict, ``False`` otherwise.
    ÚcountsÚsize)rZ   r×   ©rÏ   s    r(   rØ   rØ   �  s)   € õ �l¥DÑ)Ô)Ða¨h¸,Ð.FÐaÈ6ÐUaÐKaÐar*   Úsegmentationsú	list[Any]rÝ   rÜ   r   c                óô  — ddl m} g }| D �]¡}|�(t          |t          ¦  «        sIt	          |¦  «        dk    r6|                     t          j        ||ft          j        ¬¦  «        ¦  «         Œct          |¦  «        rˆ|d         }t          |t          t          t          f¦  «        s%t          dt          |¦  «        j        ›d�¦  «        ‚t          |t          t          f¦  «        r|g}n0|                     |||¦  «        g}n|                     |||¦  «        }|                     |¦  «        }|j        dk     r|d         }t          j        |t          j        ¬¦  «        }|                     d	¬
¦  «                             t          j        ¦  «        }|                     |¦  «         �Œ£t	          |¦  «        dk    r#t          j        d||ft          j        ¬¦  «        S t          j        |d¬
¦  «        S )a¸  Convert COCO segmentation annotations to a binary mask tensor of shape ``[N, H, W]``.

    Supports both polygon and RLE (Run-Length Encoding) annotation formats. Polygon annotations (lists of coordinate
    arrays) are rasterised via ``pycocotools.mask.frPyObjects``.  RLE annotations (dicts with ``"counts"`` and
    ``"size"`` keys; ``counts`` may be str or bytes for compressed RLE, or list of ints for uncompressed RLE) are
    decoded directly, skipping the polygon-to-RLE conversion step.

    Args:
        segmentations: Per-instance segmentation annotations.  Each element is
            either a polygon list (``[[x1, y1, x2, y2, ...], ...]``), an RLE dict (``{"counts": ..., "size": [H, W]}``),
            or ``None`` / empty for instances without a mask. Dicts must be valid COCO RLE annotations with non-empty
            ``"counts"`` and ``"size"`` fields.
        height: Image height in pixels (used for polygon rasterisation).
        width: Image width in pixels (used for polygon rasterisation).

    Returns:
        A ``uint8`` tensor of shape ``(N, H, W)`` where each slice is a binary mask for one instance.  Returns a ``(0,
        H, W)`` tensor when *segmentations* is empty.
    r   N©Údtyperà   z-RLE segmentation has unsupported counts type z; expected str, bytes, or listr±   ).Nr°   ©Údim)Úpycocotools.maskÚmaskrZ   r×   r˜   ÚappendÚtorchÚzerosÚuint8rØ   r!   Úbytesr—   rJ   ÚtypeÚ__name__ÚfrPyObjectsÚdecodeÚndimÚ	as_tensorÚanyÚtoÚstack)	rã   rÝ   rÜ   Ú	coco_maskÚmasksrÏ   rà   Úrlesrë   s	            r(   Úconvert_coco_poly_to_maskrý   �  sí  € ð( )Ð(Ð(Ð(Ð(Ð(à€EØ%ð ñ ˆØÐ­
°<ÅÑ(FÔ(FÐÍ3È|ÑK\ÔK\Ð`aÒKaÐKaà�LŠL�œ f¨e _½E¼KÐHÑHÔHÑIÔIÐIØÝ�<Ñ Ô ð 	FØ! (Ô+ˆFÝ˜f¥s­Eµ4Ð&8Ñ9Ô9ð Ý ð3ÅDÈÁLÄLÔDYð 3ð 3ð 3ñô ð õ ˜&¥3­ ,Ñ/Ô/ð Là$�~��ð "×-Ò-¨l¸FÀEÑJÔJÐK��à×(Ò(¨°v¸uÑEÔEˆDØ×Ò Ñ%Ô%ˆØŒ9�qŠ=ˆ=Ø˜	”?ˆDÝŒ˜t­5¬;Ð7Ñ7Ô7ˆà�xŠx˜Aˆx‰Œ×!Ò!¥%¤+Ñ.Ô.ˆØ�Š�TÑÔÐÑÝ
ˆ5�z„z�Q‚€ÝŒ{˜A˜v uÐ-µU´[ÐAÑAÔAÐAÝŒ;�u !Ð$Ñ$Ô$Ð$r*   c                  óB   ‡ — e Zd ZdZ	 	 	 	 	 	 ddˆ fd„Zdd„Zd d„Zˆ xZS )!ÚCocoDetectionuC  COCO detection dataset with optional sparse-to-contiguous category ID remapping.

    Extends ``torchvision.datasets.CocoDetection`` with two additions:

    1. A pluggable transform pipeline (``transforms``) applied after the raw
       annotation conversion handled by :class:`ConvertCoco`.
    2. Optional remapping of sparse COCO category IDs to contiguous 0-based label
       indices via ``remap_category_ids``.

    COCO category IDs are sparse (1â€“90 with gaps such as 12, 26, 29 â€¦).  When a model has only *N* output slots the IDs
    cannot be used directly as tensor indices â€” doing so causes out-of-bounds errors in the matcher and loss. Setting
    ``remap_category_ids=True`` builds a ``cat2label`` mapping from the annotation file so that IDs are remapped to the
    range ``[0, N)``.  The reverse ``label2cat`` mapping is attached to the underlying COCO API object so that
    :class:`~rfdetr.datasets.coco_eval.CocoEvaluator` can convert predicted label indices back to the original category
    IDs required by pycocotools.  Unannotated grouping categories â€” the synthetic root that Roboflow COCO exports
    prepend, for example â€” are excluded by :func:`filter_parent_categories` when ``include_keypoints=False``, so they
    do not consume an output slot; the keypoint path (:func:`_build_keypoint_cat2label`) keeps them.

    ``remap_category_ids`` should be ``True`` for Roboflow / custom datasets (via :func:`build_roboflow_from_coco`) and
    ``False`` (the default) when evaluating pretrained models that were trained with the convention that model output
    slot *k* corresponds directly to COCO category ID *k*.

    Args:
        img_folder: Path to the directory containing the dataset images.
        ann_file: Path to the COCO-format JSON annotation file.
        transforms: Transform pipeline applied to ``(image, target)`` pairs after
            annotation conversion.  ``None`` means no additional transforms.
        include_masks: If ``True``, decode polygon segmentation masks into binary
            tensors and include them in the target dict under the ``"masks"`` key.
        include_keypoints: If ``True``, parse COCO keypoints and include them in
            the target dict under the ``"keypoints"`` key.
        num_keypoints_per_class: Optional keypoint schema describing the number of
            keypoints per class. When provided, keypoints are padded/truncated to ``max(num_keypoints_per_class)``.
        remap_category_ids: If ``True``, build a ``cat2label`` mapping from the
            annotation file that remaps sparse category IDs to contiguous 0-based label indices.  The reverse mapping is
            stored as ``label2cat`` on both this object and the underlying COCO API object.  Defaults to ``False``.
        cat2label: Pre-built ``category_id`` â†’ label-index mapping to adopt verbatim instead of deriving one from this
            split's own annotations.  Requires ``remap_category_ids=True`` and takes precedence over both the detection
            and the keypoint derivation.  :func:`build_roboflow_from_coco` passes the train split's mapping here so
            that validation and test splits share one label space (see :func:`_train_split_cat2label`); ``None`` (the
            default) keeps the split-local derivation.
        draft_size: Smallest source extent the transform pipeline can consume without upscaling, used to enable
            JPEG DCT-domain downscaling during decode (see :meth:`_decode_image`).  ``None`` (the default) decodes at
            full resolution.  :func:`draft_size_for_transforms` derives the value from the pipeline's scales.
    FNÚ
img_folderú
str | PathÚann_fileÚ
transformsú
Any | NonerÃ   r#   Úinclude_keypointsrˆ   r‰   Úremap_category_idsr£   re   Ú
draft_sizerG   r"   ÚNonec
                óÚ  •‡ — t          ¦   «                              ||¦  «         |‰ _        |	‰ _        |‰ _        |‰ _        |�|st          d¦  «        ‚‰  ‰  |�re|�t          |¦  «        ‰ _        �n|rt          ‰ j
        |¦  «        ‰ _        nöd„ ‰ j
        j                             ¦   «         D ¦   «         }
t          t          ‰ j
        j                             ¦   «         ¦  «        |
¦  «        }d„ t!          |¦  «        D ¦   «         ‰ _        t#          t%          ‰ j
        j        ¦  «        t%          ‰ j        ¦  «        z
  ¦  «        }|r:t&                               dd                     ˆ fd„|D ¦   «         ¦  «        ¦  «         d„ ‰ j                             ¦   «         D ¦   «         ‰ _        ‰ j        ‰ j
        _        nd ‰ _        d ‰ _        t1          ||‰ j        |¬¦  «        ‰ _        d S )	Nz³cat2label was supplied but remap_category_ids is False, so the mapping would be ignored. Pass remap_category_ids=True to apply it, or drop cat2label to keep raw COCO category ids.c                ó8   — h | ]}t          |d          ¦  «        ’ŒS r4   r6   r8   s     r(   r;   z)CocoDetection.__init__.<locals>.<setcomp>"  s%   € ÐfÐfÐfÀ
�S ¨MÔ!:Ñ;Ô;ÐfÐfÐfr*   c                ó@   — i | ]\  }}t          |d          ¦  «        |“ŒS ri   r6   rj   s      r(   rl   z*CocoDetection.__init__.<locals>.<dictcomp>$  s*   € Ð!dÐ!dÐ!dÁÀÈ¥# h¨t¤nÑ"5Ô"5°uÐ!dÐ!dÐ!dr*   zNSkipping unannotated COCO grouping categories when assigning label indices: %sz, c              3  óT   •K  — | ]"}|› d ‰j         j        |         d         › d�V — Œ#dS )z (rA   ú)N)ry   r�   )r9   r   Úselfs     €r(   r‘   z)CocoDetection.__init__.<locals>.<genexpr>)  sC   øè è € Ð!gÐ!gÐU[ VÐ"PÐ"P¨t¬y¬~¸fÔ/EÀfÔ/MÐ"PÐ"PÐ"PÐ!gÐ!gÐ!gÐ!gÐ!gÐ!gr*   c                ó   — i | ]\  }}||“Œ	S rX   rX   )r9   r   rk   s      r(   rl   z*CocoDetection.__init__.<locals>.<dictcomp>,  s   € ÐXÐXÐX±°¸˜e VÐXÐXÐXr*   )rÃ   r  r£   rˆ   )ÚsuperÚ__init__Ú_transformsÚ_draft_sizerÃ   r  rJ   r×   r£   r¥   ry   rƒ   r„   rc   r—   r�   rp   r^   r_   rr   ÚinfoÚjoinr‚   Ú	label2catÚConvertCocoÚprepare)r  r   r  r  rÃ   r  rˆ   r  r£   r  r\   rb   ÚdroppedÚ	__class__s   `            €r(   r  zCocoDetection.__init__  sï  øø€ õ 	‰Œ×Ò˜ XÑ.Ô.Ð.Ø%ˆÔØ%ˆÔØ*ˆÔØ!2ˆÔØÐ Ð);Ð Ýðmñô ð ð 	Ð-ØÐ-Øñ 	"àÐ$Ý!% i¡¤�”‘Ø"ð Ý!:¸4¼9ÐF]Ñ!^Ô!^�”�àfÐfÈdÌiÌn×NcÒNcÑNeÔNeÐfÑfÔf�	Ý/µ°T´Y´^×5JÒ5JÑ5LÔ5LÑ0MÔ0MÈyÑYÔY�Ø!dÐ!dÕT]Ð^bÑTcÔTcÐ!dÑ!dÔ!d�”Ý ¥ T¤Y¤^Ñ!4Ô!4µs¸4¼>Ñ7JÔ7JÑ!JÑKÔK�Øð Ý—K’KØhØŸ	š	Ð!gÐ!gÐ!gÐ!gÐ_fÐ!gÑ!gÔ!gÑgÔgñô ð ð
 YÐXÀÄ×AUÒAUÑAWÔAWÐXÑXÔXˆDŒNà"&¤.ˆDŒIÔÐà!ˆDŒNØ!ˆDŒNÝ"Ø'Ø/Ø”nØ$;ð	
ñ 
ô 
ˆŒˆˆr*   Úimage_idr7   ú'tuple[Image.Image, tuple[float, float]]c                óÔ   — | j                              |¦  «        d         d         }t          t          | j        ¦  «        |z  | j        ¦  «        \  }}t          j        |¦  «        |fS )aä  Decode one image through :func:`decode_image`, drafting when ``draft_size`` is set.

        Used instead of ``torchvision.datasets.CocoDetection._load_image``, which this class no longer calls, and
        deliberately not named the same: it returns a decode scale alongside the image.

        Args:
            image_id: COCO image id.

        Returns:
            Decoded RGB image and its horizontal/vertical decode scales, both ``1.0`` when the decoder did not reduce.
        r   Ú	file_name)ry   ÚloadImgsr   r   Úrootr  r
   Ú	fromarray)r  r  ÚpathÚpixelsr½   s        r(   Ú_decode_imagezCocoDetection._decode_image9  s[   € ð Œy×!Ò! (Ñ+Ô+¨AÔ.¨{Ô;ˆÝ%¥d¨4¬9¡o¤o¸Ñ&<¸dÔ>NÑOÔO‰ˆ�ÝŒ˜vÑ&Ô&¨Ð.Ð.r*   r�   útuple[Any, Any]c                ó2  ‡‡— | j         |         }|                      |¦  «        \  }\  ŠŠ|                      |¦  «        }‰‰fdk    rˆˆfd„|D ¦   «         }||dœ}|                      ||¦  «        \  }}| j        �|                      ||¦  «        \  }}||fS )N)ç      ð?r'  c                ó2   •— g | ]}t          |‰‰¦  «        ‘ŒS rX   )rÞ   )r9   r:   rÉ   rË   s     €€r(   rV   z-CocoDetection.__getitem__.<locals>.<listcomp>N  s'   ø€ ÐmÐmÐmÐS]Õ0°¸WÀgÑNÔNÐmÐmÐmr*   )r  r   )Úidsr$  Ú_load_targetr  r  )r  r�   r  Úimgr   ÚtargetrÉ   rË   s         @@r(   Ú__getitem__zCocoDetection.__getitem__I  s¾   øø€ Ø”8˜C”=ˆØ"&×"4Ò"4°XÑ">Ô">ÑˆÑˆg�wØ×'Ò'¨Ñ1Ô1ˆØ�WÐ Ò+Ð+ØmÐmÐmÐmÐmÐalÐmÑmÔmˆKØ&°{ÐCÐCˆØ—l’l 3¨Ñ/Ô/‰ˆˆVØÔÐ'ð ×*Ò*¨3°Ñ7Ô7‰KˆC�Ø�Fˆ{Ðr*   )FFNFNN)r   r  r  r  r  r  rÃ   r#   r  r#   rˆ   r‰   r  r#   r£   re   r  rG   r"   r  )r  r7   r"   r  )r�   r7   r"   r%  )rò   Ú
__module__Ú__qualname__Ú__doc__r  r$  r-  Ú__classcell__)r  s   @r(   rÿ   rÿ   Ô  sŠ   ø€ € € € € ð,ð ,ðf $Ø"'Ø48Ø#(Ø+/Ø!%ð4
ð 4
ð 4
ð 4
ð 4
ð 4
ð 4
ðl/ð /ð /ð /ð ð ð ð ð ð ð ð r*   rÿ   c                  ó,   — e Zd ZdZ	 	 	 	 ddd„Zdd„ZdS )r  uð  Convert a raw COCO annotation dict into model-ready tensors.

    Accepts the ``(image, target)`` pair produced by ``torchvision.datasets.CocoDetection`` and returns the same image
    alongside a target dict containing:

    - ``"boxes"`` â€“ ``(N, 4)`` float32 tensor in absolute ``[x_min, y_min, x_max, y_max]`` format.
    - ``"labels"`` â€“ ``(N,)`` int64 tensor of class indices.
    - ``"image_id"`` â€“ scalar int64 tensor.
    - ``"area"`` â€“ ``(N,)`` float32 tensor of annotation areas (used by COCO eval).
    - ``"iscrowd"`` â€“ ``(N,)`` int64 tensor (0 = instance, 1 = crowd).
    - ``"masks"`` â€“ ``(N, H, W)`` bool tensor of binary segmentation masks, only
      present when ``include_masks=True``.
    - ``"keypoints"`` â€“ ``(N, K, 3)`` float32 tensor in COCO keypoint format,
      only present when ``include_keypoints=True``.

    Crowd annotations (``iscrowd=1``) and degenerate boxes (zero width or height after clamping to image boundaries) are
    filtered out.

    Args:
        include_masks: If ``True``, decode segmentation annotations (polygon or
            RLE format) into binary masks and include them in the returned target dict.
        cat2label: Optional mapping from COCO ``category_id`` values to contiguous
            0-based label indices.  When ``None`` (default) the raw ``category_id`` values are used as labels directly,
            which is correct for datasets whose IDs are already 0-indexed.  Pass a non-``None`` mapping for sparse
            COCO-style datasets (e.g. IDs 1â€“90 with gaps) so that labels stay within the model's output range.
        num_keypoints_per_class: Optional keypoint schema. When provided, keypoints
            are padded/truncated to ``max(num_keypoints_per_class)`` in each annotation.
    FNrÃ   r#   r  r£   re   rˆ   r‰   r"   r  c                ód   — || _         || _        || _        |�t          |d¬¦  «        nd| _        d S )Nr   )Údefault)rÃ   r  r£   rš   r€   )r  rÃ   r  r£   rˆ   s        r(   r  zConvertCoco.__init__v  sB   € ð +ˆÔØ!2ˆÔØ"ˆŒØH_ÐHk�SÐ!8À!ÐDÑDÔDÐDÐqrˆÔÐÐr*   ÚimageúImage.Imager,  r0   ú"tuple[Image.Image, dict[str, Any]]c           	     óN
  — |j         \  }}|d         }t          j        |g¦  «        }|d         }d„ |D ¦   «         }d„ |D ¦   «         }t          j        |t          j        ¬¦  «                             dd¦  «        }|d d …dd …fxx         |d d …d d…f         z  cc<   |d d …d	d d…f                              d	|¬
¦  «         |d d …dd d…f                              d	|¬
¦  «         g }	| j        }
|D ]j}|d         }|
�I||
vr)t          d|› d|                     d¦  «        › d�¦  «        ‚|	 	                    |
|         ¦  «         ŒU|	 	                    |¦  «         Œkt          j        |	t          j
        ¬¦  «        }|d d …df         |d d …df         k    |d d …df         |d d …d	f         k    z  }||         }||         }i }||d<   ||d<   ||d<   t          j        d„ |D ¦   «         t          j        ¬¦  «        }t          j        d„ |D ¦   «         t          j
        ¬¦  «        }||         |d<   ||         |d<   d }| j        �r•| j        }|d	k    r0|D ]-}|                     d¦  «        }|�t          |¦  «        dz  } nŒ.g }|D ]û}|                     d¦  «        }|€6| 	                    t          j        |dft          j        ¬¦  «        ¦  «         ŒOt          j        |t          j        ¬¦  «                             dd¦  «        }|j        d	         |k     rJt          j        |dft          j        ¬¦  «        }||d |j        d	         …<   | 	                    |¦  «         ŒÞ| 	                    |d |…         ¦  «         Œüt          |¦  «        d	k    rt          j        |d	¬¦  «        }n#t          j        d	|dft          j        ¬¦  «        }||         |d<   | j        rÛt          |¦  «        d	k    rrd|d	         v rhd„ |D ¦   «         }t%          |||¦  «        }|                     ¦   «         d	k    r||         |d<   nMt          j        d	||ft          j        ¬¦  «        |d<   n&t          j        d	||ft          j        ¬¦  «        |d<   |d                              ¦   «         |d<   |�|d         |         |d<   t          j        t-          |¦  «        t-          |¦  «        g¦  «        |d<   t          j        t-          |¦  «        t-          |¦  «        g¦  «        |d<   ||fS )Nr  r   c                ó2   — g | ]}d |vs|d          dk    ¯|‘ŒS ©Úiscrowdr   rX   ©r9   Úobjs     r(   rV   z(ConvertCoco.__call__.<locals>.<listcomp>Š  s1   € ÐSÐSÐS˜ y¸Ð';Ð';¸sÀ9¼~ÐQRÒ?RÐ?R�Ð?RÐ?RÐ?Rr*   c                ó   — g | ]
}|d          ‘ŒS )rÍ   rX   r<  s     r(   rV   z(ConvertCoco.__call__.<locals>.<listcomp>Œ  s   € Ð2Ð2Ð2 c�c˜&”kÐ2Ð2Ð2r*   ræ   r¯   r§   r°   r   )Úminrš   r’   r5   zUnknown category_id z for image_id zR encountered in annotations. Check that your category mapping matches the dataset.r±   ÚboxesÚlabelsc                ó   — g | ]
}|d          ‘ŒS )rÎ   rX   r<  s     r(   rV   z(ConvertCoco.__call__.<locals>.<listcomp>¬  s   € Ð<Ð<Ð<°  F¤Ð<Ð<Ð<r*   c                ó*   — g | ]}d |v r|d          nd‘ŒS r:  rX   r<  s     r(   rV   z(ConvertCoco.__call__.<locals>.<listcomp>­  s+   € Ð"]Ð"]Ð"]ÐQT°YÀ#Ð5EÐ5E 3 y¤> >È1Ð"]Ð"]Ð"]r*   rÎ   r;  r}   rè   rÏ   c                ó:   — g | ]}|                      d g ¦  «        ‘ŒS râ   r<   r<  s     r(   rV   z(ConvertCoco.__call__.<locals>.<listcomp>×  s&   € Ð MÐ MÐ MÀ §¢¨¸Ñ!<Ô!<Ð MÐ MÐ Mr*   rû   Ú	orig_sizerá   )rá   rí   rö   Úfloat32ÚreshapeÚclamp_r£   rD   r=   rì   Úint64r  r€   r˜   rî   Úshaperù   rÃ   rý   Únumelrï   r#   r7   )r  r5  r,  ÚwÚhr  ÚannoÚ
box_valuesr@  Ú	class_idsr£   r=  r5   ÚclassesÚkeeprÎ   r;  Úkeypoint_keepr€   r}   Úkeypoint_tensorsÚraw_keypointsÚkeypoint_tensorÚpaddedÚkeypoints_outrã   rû   s                              r(   Ú__call__zConvertCoco.__call__‚  s¥  € ØŒz‰ˆˆ1à˜*Ô%ˆÝ”? H :Ñ.Ô.ˆà�mÔ$ˆàSÐS˜tÐSÑSÔSˆà2Ð2¨TÐ2Ñ2Ô2ˆ
å” 
µ%´-Ð@Ñ@Ô@×HÒHÈÈQÑOÔOˆØˆaˆaˆa���ˆeˆˆŒ˜˜a˜a˜a  ! ˜eœÑ$ˆˆ‰Øˆaˆaˆa���A�ˆgŒ×Ò !¨ÐÑ+Ô+Ð+Øˆaˆaˆa���A�ˆgŒ×Ò !¨ÐÑ+Ô+Ð+à!ˆ	Ø”Nˆ	Øð 
	.ð 
	.ˆCØ˜mÔ,ˆKØÐ$Ø iÐ/Ð/Ý"ðl¨{ð lð lÈ&Ï*Ê*ÐU_ÑJ`ÔJ`ð lð lð lñô ð ð × Ò  ¨;Ô!7Ñ8Ô8Ð8Ð8à× Ò  Ñ-Ô-Ð-Ð-Ý”/ )µ5´;Ð?Ñ?Ô?ˆà�a�a�a˜�d”˜e A A A q DœkÒ)¨e°A°A°A°q°D¬k¸EÀ!À!À!ÀQÀ$¼KÒ.GÑHˆØ�d”ˆØ˜$”-ˆàˆØˆˆw‰Ø"ˆˆxÑØ%ˆˆzÑõ ŒÐ<Ð<°tÐ<Ñ<Ô<ÅEÄMÐRÑRÔRˆÝ”/Ð"]Ð"]ÐX\Ð"]Ñ"]Ô"]ÕejÔepÐqÑqÔqˆØ˜dœˆˆv‰Ø# DœMˆˆyÑà'+ˆØÔ!ñ 	6Ø Ô.ˆMØ Ò!Ð!Øð ð �CØ #§¢¨Ñ 4Ô 4�IØ Ð,Ý(+¨I©¬¸!Ñ(;˜Ø˜ð -ð .0ÐØð Ið I�Ø #§¢¨Ñ 4Ô 4�Ø Ð(Ø$×+Ò+­E¬K¸ÈÐ8JÕRWÔR_Ð,`Ñ,`Ô,`ÑaÔaÐaØå"'¤/°-ÅuÄ}Ð"UÑ"UÔ"U×"]Ò"]Ð^`ÐbcÑ"dÔ"d�Ø"Ô(¨Ô+¨mÒ;Ð;Ý"œ[¨-¸Ð);Å5Ä=ÐQÑQÔQ�FØ9H�FÐ5˜_Ô2°1Ô5Ð5Ñ6Ø$×+Ò+¨FÑ3Ô3Ð3ØØ ×'Ò'¨¸¸¸Ô(GÑHÔHÐHÐHåÐ#Ñ$Ô$ qÒ(Ð(Ý %¤Ð,<À!Ð DÑ DÔ D��å %¤¨Q°¸qÐ,AÍÌÐ WÑ WÔ W�Ø"/°Ô"5ˆF�;Ñð Ôð 	AÝ�4‰yŒy˜1Š}ˆ} °4¸´7Ð!:Ð!:Ø MÐ MÈÐ MÑ MÔ M�Ý1°-ÀÀAÑFÔF�Ø—;’;‘=”= 1Ò$Ð$Ø&+¨D¤k�F˜7‘O�Oå&+¤k°1°a¸°)Å5Ä;Ð&OÑ&OÔ&O�F˜7‘O�Oå"'¤+¨q°!°Q¨i½u¼{Ð"KÑ"KÔ"K��w‘à$ Wœo×2Ò2Ñ4Ô4ˆF�7‰OØÐ(Ø"(¨¤/°-Ô"@��w‘å#œo­s°1©v¬vµs¸1±v´vÐ.>Ñ?Ô?ˆˆ{ÑÝœ­#¨a©&¬&µ#°a±&´&Ð)9Ñ:Ô:ˆˆv‰à�fˆ}Ðr*   )FFNN)
rÃ   r#   r  r#   r£   re   rˆ   r‰   r"   r  )r5  r6  r,  r0   r"   r7  )rò   r.  r/  r0  r  rY  rX   r*   r(   r  r  X  sd   € € € € € ðð ð> $Ø"'Ø+/Ø48ð
sð 
sð 
sð 
sð 
sðeð eð eð eð eð er*   r  T)Úmax_sizerÂ   r½   ÚsquarerZ  c               ó   — |r-ddd„ | D ¦   «         ii}ddddg d¢iiddd„ | D ¦   «         iigii}nR|pt           }t          | ¦  «        d	k    r| d
         n| }dddd|iidd|iigii}ddddg d¢iiddd„ | D ¦   «         iigii}|s|gS dd||giigS )u½  Build the training resize pipeline as an Albumentations config list.

    Expresses the ``RandomSelect(resize_a, Compose([resize_b1, crop, resize_b2]))`` pattern as a config-driven
    ``OneOf``/``Sequential`` for use with :meth:`AlbumentationsWrapper.from_config`.

    Two branches are selected with equal probability:

    - **Option A** â€“ direct resize to the target scale(s).
    - **Option B** â€“ resize to an intermediate scale (400/500/600 px), crop,
      then resize to the target scale.

    Divisibility padding (rounding ``H``/``W`` up to a multiple of ``patch_size * num_windows``) is handled by the batch
    collator via :func:`~rfdetr.utilities.tensors.make_collate_fn`, not here.

    Args:
        scales: Target resize scales in pixels.
        square: If ``True``, produce square output using ``A.Resize``
            (one random scale from *scales*).  If ``False``, preserve aspect ratio using ``A.SmallestMaxSize`` with an
            optional long-side cap.
        max_size: Maximum long-side size for non-square resizes.  Defaults to
            ``1333`` when *square* is ``False``.
        scale_jitter: If ``True`` (default), both Option A and Option B are randomly
            selected.  If ``False``, only Option A (direct resize) is used â€” no random crop.

    Returns:
        A single-element list. By default the entry wraps a ``OneOf`` over both
        branches; when ``scale_jitter=False``, the entry is Option A directly.
    ÚOneOfr  c                ó   — g | ]	}d ||dœi‘Œ
S )r   ©rÝ   rÜ   rX   ©r9   Úss     r(   rV   z._build_train_resize_config.<locals>.<listcomp>  s%   € ÐUÐUÐUÈ °QÀÐ*CÐ*CÐDÐUÐUÐUr*   Ú
SequentialÚSmallestMaxSizerZ  ©i�  iô  rÆ   c                ó"   — g | ]}d ddg||dœi‘ŒS ©r   é€  rÆ   )Úmin_max_heightrÝ   rÜ   rX   r`  s     r(   rV   z._build_train_resize_config.<locals>.<listcomp>  ó=   € ð +ð +ð +à$%ð "3ÈÈSÀzÐ]^ÐijÐ4kÐ4kÐ lð+ð +ð +r*   r’   r   ÚCappedLongestMaxSizec                ó"   — g | ]}d ddg||dœi‘ŒS rf  rX   r`  s     r(   rV   z._build_train_resize_config.<locals>.<listcomp>>  ri  r*   )Ú_COCO_MAX_SIZEr˜   )r½   r[  rZ  rÂ   Úoption_aÚoption_bÚcapÚ
size_params           r(   Ú_build_train_resize_configrq  ê  sd  € ðF ð 9
àØÐUÐUÈfÐUÑUÔUðð$
ˆð ØØ&¨°_°_°_Ð(EÐFàØ(ð +ð +à)/ð+ñ +ô +ð"ðð
ðð$
ˆˆð  Ð(�.ˆå'*¨6¡{¤{°aÒ'7Ð'7˜& œ)˜)¸Vˆ
àØØ&¨°ZÐ(@ÐAð ,¨j¸#Ð->Ð?ððð

ˆð& ØØ&¨°_°_°_Ð(EÐFàØ(ð +ð +à)/ð+ñ +ô +ð"ðð
ðð
ˆð  ð ØˆzÐà�| h°Ð%9Ð:Ð;Ð<Ð<r*   ú	List[int]úOptional[int]ú4Compose | RandomChoice | RandomResize | RandomSelectc               ó¶  ‡— |rdt          d„ | D ¦   «         ¦  «        }|s|S t          t          g d¢¦  «        t          d„ | D ¦   «         ¦  «        g¦  «        }t          ||¦  «        S |pt          Št          | ‰¬¦  «        }|s|S ˆfd„| D ¦   «         }t          t          g d¢¦  «        t          d„ |D ¦   «         ¦  «        g¦  «        }t          ||¦  «        S )u{  Build the default torchvision-native training resize pipeline.

    Args:
        scales: Candidate target scales.
        square: Whether to force square resize outputs.
        max_size: Optional maximum long-side size for non-square resizing.
        scale_jitter: If ``True`` (default), randomly picks between a direct resize
            (Option A) and a resize â†’ crop â†’ resize sequence (Option B). If ``False``,
            only Option A is used â€” no random crop.

    Returns:
        Random two-branch resize transform matching the historical DETR-style pipeline,
        or just Option A when ``scale_jitter=False``.
    c                ó0   — g | ]}t          ||f¦  «        ‘ŒS rX   )r   ©r9   rº   s     r(   rV   z2_build_train_resize_transforms.<locals>.<listcomp>d  s$   € Ð%QÐ%QÐ%QÀ¥f¨e°U¨^Ñ&<Ô&<Ð%QÐ%QÐ%Qr*   rd  c                ó2   — g | ]}t          d ||f¦  «        ‘ŒS ©)rg  rÆ   ©r   rw  s     r(   rV   z2_build_train_resize_transforms.<locals>.<listcomp>k  s&   € ÐUÐUÐUÀU•_ Z°%¸°Ñ@Ô@ÐUÐUÐUr*   ©rZ  c                ó0   •— g | ]}t          |‰¦  «        ‘ŒS rX   )r?  )r9   rº   ro  s     €r(   rV   z2_build_train_resize_transforms.<locals>.<listcomp>y  s!   ø€ Ð9Ð9Ð9¨•S˜ ‘_”_Ð9Ð9Ð9r*   c                ó2   — g | ]}t          d ||f¦  «        ‘ŒS ry  rz  rw  s     r(   rV   z2_build_train_resize_transforms.<locals>.<listcomp>}  s&   € ÐaÐaÐaÈ%�/¨*°u¸e°nÑEÔEÐaÐaÐar*   )r   r   r   r   rl  )	r½   r[  rZ  rÂ   Úsquare_resizeÚresize_bÚresizeÚcapped_scalesro  s	           @r(   Ú_build_train_resize_transformsr‚  N  s  ø€ ð* ð 5Ý$Ð%QÐ%QÈ&Ð%QÑ%QÔ%QÑRÔRˆØð 	!Ø Ð Ýå˜_˜_˜_Ñ-Ô-ÝØUÐUÈfÐUÑUÔUñô ðñ
ô 
ˆõ ˜M¨8Ñ4Ô4Ð4à
Ð
$•n€CÝ˜&¨3Ð/Ñ/Ô/€FØð Øˆð
 :Ð9Ð9Ð9°&Ð9Ñ9Ô9€MÝå˜˜˜Ñ)Ô)ÝÐaÐaÐS`ÐaÑaÔaÑbÔbð	
ñô €Hõ ˜ Ñ)Ô)Ð)r*   )rÂ   Ú
aug_configú#Optional[Dict[str, Dict[str, Any]]]Úgpu_postprocessÚkeypoint_flip_pairsúOptional[List[int]]r   c               óR  — t          ¦   «         }t          t          j        d¬¦  «        }	t	          ¦   «         }
| dk    rxt          j        t          |||rdnt          |¬¦  «        ¦  «        }g |¢}|s&t          j        |�|nt          |¬¦  «        }|g |¢z  }|||	gz  }|s||
gz  }t          |¦  «        S |s| dk    r1t          j        d||d	œig¦  «        }t          g |¢|‘|	‘|
‘¦  «        S t          j        d
d|iiddt          iig¦  «        }t          g |¢|‘|	‘|
‘¦  «        S )uõ  Build the legacy Albumentations-backed transform pipeline for custom configs.

    Args:
        image_set: Dataset split name.
        resolution: Target resolution.
        scales: Candidate train resize scales.
        square: Whether to use square resize.
        aug_config: Custom Albumentations config.
        scale_jitter: If ``True`` (default), the training resize pipeline randomly picks between
            a direct resize (Option A) and a resize â†’ crop â†’ resize sequence (Option B). Set to
            ``False`` to use Option A only â€” no random crop.
        gpu_postprocess: Whether GPU augmentation/normalization will run later.
        keypoint_flip_pairs: Keypoint left/right swap pairs.

    Returns:
        Transform pipeline.
    T©rº   r%   N©r[  rZ  rÂ   )r†  Ú	val_speedr   r_  rc  rZ  rj  )r   r   rí   rF  r   r   Úfrom_configrq  rl  r   r   )rÄ   r¨   r½   r[  rƒ  rÂ   r…  r†  Úto_imageÚto_floatÚ	normalizeÚresize_wrappersÚpipelineÚaug_wrapperss                 r(   Ú_build_albumentations_pipeliner“  ƒ  s™  € õ8 ‰yŒy€HÝ•u”}¨DÐ1Ñ1Ô1€HÝ‘”€Ià�GÒÐÝ/Ô;Ý&ØØØ!'Ð;˜˜­^Ø)ð	ñ ô ñ
ô 
ˆð 1 Ð0ˆØð 	(Ý0Ô<Ø(Ð4�
�
½*Ø$7ðñ ô ˆLð ˜˜,˜Ñ'ˆHØ�X˜xÐ(Ñ(ˆØð 	$Ø˜˜Ñ#ˆHÝ�xÑ Ô Ð àð J�˜kÒ)Ð)Ý/Ô;¸hÐS]ÐhrÐHsÐHsÐ=tÐ<uÑvÔvˆÝÐH˜ÐH¨(ÐH°HÐH¸iÐHÑIÔIÐIå+Ô7à ¨ZÐ 8Ð9ð $ jµ.Ð%AÐBð		
ñô €Oõ ÐD�_ÐD hÐD°ÐD¸)ÐDÑEÔEÐEr*   c               ón  — t          ¦   «         }t          t          j        d¬¦  «        }	t	          ¦   «         }
| dk    r§ddl}|€|                     dt          d¬¦  «         t          |||rdnt          |¬	¦  «        g}|€G|sE|�|st          d
t          j        d¬¦  «         n$|                     t          d|¬¦  «        ¦  «         |||	gz  }|s||
gz  }t          |¦  «        S |s| dk    r"t          t!          ||f¦  «        ||	|
g¦  «        S t          t#          |gt          ¬¦  «        ||	|
g¦  «        S )uû  Build the default torchvision-native transform pipeline.

    Args:
        image_set: Dataset split name.
        resolution: Target resolution.
        scales: Candidate train resize scales.
        square: Whether to use square resize.
        aug_config: ``None`` for default augmentation, ``{}`` to disable it.
        scale_jitter: If ``True`` (default), the training resize pipeline randomly picks between
            a direct resize (Option A) and a resize â†’ crop â†’ resize sequence (Option B). Set to
            ``False`` to use Option A only â€” no random crop.
        gpu_postprocess: Whether GPU augmentation/normalization will run later.
        keypoint_flip_pairs: Keypoint left/right swap pairs.

    Returns:
        Transform pipeline.
    Tr‰  r%   r   Naz  RF-DETR has changed the default training augmentation backend from Albumentations (cv2 INTER_LINEAR, no antialias) to torchvision (BILINEAR + antialias=True). Pixel values will differ slightly from previous versions; mAP may drift on existing benchmarks. To restore the previous behaviour, install rfdetr[augment] and pass aug_config=AUG_CONFIG from rfdetr.datasets.aug_configs.r§   )Ú
stacklevelrŠ  r   F)Úeditable_configg      à?)Úpr†  r‹  r{  )r   r   rí   rF  r   ÚwarningsÚwarnÚUserWarningr‚  rl  r   rr   rs   rì   r   r   r   r   )rÄ   r¨   r½   r[  rƒ  rÂ   r…  r†  r�  rŽ  r�  r˜  r‘  s                r(   Ú_build_torchvision_pipeliner›  Ç  s…  € õ8 ‰yŒy€HÝ•u”}¨DÐ1Ñ1Ô1€HÝ‘”€Ià�GÒÐØˆˆˆàÐØ�MŠMðOõ Øð ñ 	ô 	ð 	õ +ØØØ!'Ð;˜˜­^Ø)ð	ñ ô ð
ˆð Ð oÐØ"Ð.Ð7JÐ.õ .Ð.DÅfÄnÐfkÐlÑlÔlÐlÐlà—’Õ 4°sÐPcÐ dÑ dÔ dÑeÔeÐeØ�X˜xÐ(Ñ(ˆØð 	$Ø˜˜Ñ#ˆHÝ�xÑ Ô Ð àð Z�˜kÒ)Ð)Ý� 
¨JÐ7Ñ8Ô8¸(ÀHÈiÐXÑYÔYÐYÝ•L * ½ÐGÑGÔGÈÐS[Ð]fÐgÑhÔhÐhr*   c          
     óz   — | dk    r|di fvr|st          | |||||||¬¦  «        S t          | |||||||¬¦  «        S )u  Route transform construction to Albumentations or torchvision backend.

    Args:
        image_set: Dataset split name.
        resolution: Target resolution in pixels.
        scales: Candidate resize scales.
        square: Whether to use square resize.
        aug_config: Augmentation config; ``None`` or ``{}`` routes to torchvision.
        scale_jitter: If ``True`` (default), the training resize pipeline randomly picks between
            a direct resize (Option A) and a resize â†’ crop â†’ resize sequence (Option B). Set to
            ``False`` to use Option A only â€” no random crop.
        gpu_postprocess: Whether GPU augmentation will run later.
        keypoint_flip_pairs: Keypoint left/right swap pairs.

    Returns:
        Composed transform pipeline.
    r%   N©r[  rƒ  rÂ   r…  r†  )r“  r›  )rÄ   r¨   r½   r[  rƒ  rÂ   r…  r†  s           r(   Ú_route_transformsrž    s‚   € ð8 �GÒÐ 
°4¸°*Ð <Ð <À_Ð <Ý-ØØØØØ!Ø%Ø+Ø 3ð	
ñ 	
ô 	
ð 		
õ 'ØØØØØØ!Ø'Ø/ð	ñ 	ô 	ð 	r*   Úskip_random_resizeú dict[str, dict[str, Any]] | Nonec           
     óÚ   — |g}|r:t          ||||¦  «        }|r	|d         g}t                               d|› �¦  «         | dvrt          d| › �¦  «        ‚t	          | ||d|||	|
¬¦  «        S )u©  Build the standard COCO transform pipeline for a given dataset split.

    Returns a composed transform that resizes images to the target ``resolution`` (with optional multi-scale jitter),
    applies torchvision-native default augmentations during training, and normalises pixel values with ImageNet
    statistics. Non-empty custom ``aug_config`` values continue to use the optional Albumentations path.

    For the ``"train"`` split the pipeline uses a two-branch ``OneOf`` between a direct resize and a resize â†’
    random-crop â†’ resize sequence (built via :func:`_build_train_resize_config`), followed by the
    augmentation stack and normalisation.  For ``"val"``, ``"test"``, and ``"val_speed"`` only resize
    and normalisation are applied â€” no augmentation.

    When *gpu_postprocess* is ``True``, both the Albumentations augmentation wrappers and the ``Normalize`` step are
    omitted from the ``"train"`` pipeline. The ``RFDETRDataModule`` then applies
    augmentation and normalization on the device in ``on_after_batch_transfer`` instead.

    Args:
        image_set: Dataset split identifier â€” ``"train"``, ``"val"``, ``"test"``,
            or ``"val_speed"``.
        resolution: Target short-side resolution in pixels.  During validation the
            longest side is capped at 1333 px to preserve aspect ratio.
        multi_scale: If ``True``, sample the resize target from a range of scales
            computed by :func:`compute_multi_scale_scales` instead of using a single fixed size.
        expanded_scales: Passed to :func:`compute_multi_scale_scales`; broadens the
            scale range when ``multi_scale=True``.
        skip_random_resize: When ``multi_scale=True``, use only the largest scale
            and skip random selection among multiple scales.
        patch_size: Model patch size used by :func:`compute_multi_scale_scales` to
            ensure all candidate resolutions are compatible with the backbone.
        num_windows: Number of attention windows; used by
            :func:`compute_multi_scale_scales` to derive candidate resolutions.
        aug_config: Controls the training augmentation backend.  Three states are
            recognised:

            * ``None`` (default) â€” use the torchvision-native default augmentation
              (``RandomHorizontalFlip(p=0.5)``, gated by ``keypoint_flip_pairs`` â€”
              see below).  See the ``UserWarning`` emitted at runtime for details
              of this behaviour change.
            * ``{}`` (empty dict) â€” disable all optional training augmentation
              including the default horizontal flip.
            * non-empty dict â€” pass to the optional Albumentations backend;
              requires ``rfdetr[augment]`` to be installed.

            Note:
                ``aug_config`` has no effect on ``"val"``, ``"test"``, or ``"val_speed"``
                splits â€” augmentation is never applied outside of training.
        scale_jitter: If ``True`` (default), the training resize pipeline randomly picks between
            a direct resize (Option A) and a resize â†’ crop â†’ resize sequence (Option B) for scale
            variation.  Set to ``False`` to use Option A only â€” no random crop, annotations near
            image borders stay intact.
        gpu_postprocess: When ``True``, skip CPU augmentation and
            ``Normalize`` from the CPU pipeline.  The ``RFDETRDataModule`` then applies both augmentation and
            normalization on the GPU in ``on_after_batch_transfer``.  Has no effect on val/test splits.
        keypoint_flip_pairs: Keypoint left/right swap pairs, or ``None`` for a
            detection-only pipeline.  On the torchvision-native default backend
            (``aug_config=None``), an empty list disables ``RandomHorizontalFlip``
            entirely instead of applying it without relabelling â€” mirroring
            ``AlbumentationsWrapper.from_config``'s existing gating for the same
            sentinel.

    Returns:
        A transform pipeline ready to be passed to :class:`CocoDetection`.

        .. note::
            This pipeline does **not** guarantee that output ``H`` and ``W`` are divisible by ``patch_size *
            num_windows``.  Divisibility is enforced at the batch level by the DataLoader collate function.  If you
            apply these transforms outside of :class:`~rfdetr.training.module_data.RFDETRDataModule`,
            pass the result
            through :func:`~rfdetr.utilities.tensors.nested_tensor_from_tensor_list` with ``block_size=patch_size *
            num_windows``, or use :func:`~rfdetr.utilities.tensors.make_collate_fn` with that value.

    Raises:
        ValueError: If ``image_set`` is not one of the recognised split names.
    r¯   z(Using multi-scale training with scales: ©r%   ÚvalÚtestr‹  úunknown Fr�  ©r¿   rr   r  rJ   rž  ©rÄ   r¨   rÁ   r©   rŸ  rª   r«   rƒ  rÂ   r…  r†  r½   s               r(   Úmake_coco_transformsr¨  D  s©   € ðl ˆ\€FØð Iå+¨J¸ÈÐU`ÑaÔaˆØð 	"Ø˜R”j�\ˆFÝ�ŠÐG¸vÐGÐGÑHÔHÐHàÐ=Ð=Ð=ÝÐ/ IÐ/Ð/Ñ0Ô0Ð0åØØØØØØ!Ø'Ø/ð	ñ 	ô 	ð 	r*   c           
     óÚ   — |g}|r:t          ||||¦  «        }|r	|d         g}t                               d|› �¦  «         | dvrt          d| › �¦  «        ‚t	          | ||d|||	|
¬¦  «        S )uï  Create COCO transforms with square resizing where the output size is divisible by 64.

    This function builds a torchvision-native transform pipeline for COCO images that resizes them to square shapes
    suitable for models that require spatial dimensions divisible by 64. It supports multi-scale training and optional
    random resizing and cropping for the training split. Non-empty custom ``aug_config`` values continue to use the
    optional Albumentations path.

    When *gpu_postprocess* is ``True``, both CPU augmentation and the ``Normalize`` step are
    omitted from the ``"train"`` pipeline. The ``RFDETRDataModule`` then applies augmentation and normalization on the
    device in ``on_after_batch_transfer`` instead.

    Args:
        image_set: Dataset split identifier. Expected values are "train", "val",
            "test", or "val_speed". Each split uses a slightly different transform pipeline suited for training or
            evaluation.
        resolution: Base square resolution (in pixels) to which images are resized.
        multi_scale: If True, enable multi-scale training by sampling from a set of
            square resolutions instead of a single fixed size.
        expanded_scales: If True, expand the range of scales used during
            multi-scale training. Passed through to ``compute_multi_scale_scales``.
        skip_random_resize: If True and ``multi_scale`` is enabled, use only the
            largest scale returned by ``compute_multi_scale_scales`` and skip
            random selection among multiple scales.
        patch_size: Patch size used by ``compute_multi_scale_scales`` when
            determining valid square resolutions (typically related to the model's patch embedding or stride).
        num_windows: Number of windows used by ``compute_multi_scale_scales`` to
            derive the list of candidate square resolutions.
        aug_config: ``None`` for default torchvision augmentation, ``{}`` to disable augmentation, or a non-empty
            Albumentations augmentation config dictionary.  On the ``None`` default, ``RandomHorizontalFlip`` is
            further gated by ``keypoint_flip_pairs`` (see below).

            Note:
                ``aug_config`` has no effect on ``"val"``, ``"test"``, or ``"val_speed"``
                splits â€” augmentation is never applied outside of training.
        scale_jitter: If ``True`` (default), the training resize pipeline randomly picks between
            a direct resize (Option A) and a resize â†’ crop â†’ resize sequence (Option B) for scale
            variation.  Set to ``False`` to use Option A only â€” no random crop, annotations near
            image borders stay intact.
        gpu_postprocess: When ``True``, skip Albumentations augmentation wrappers and
            ``Normalize`` from the CPU pipeline.  The ``RFDETRDataModule`` then applies both augmentation and
            normalization on the GPU in ``on_after_batch_transfer``.  Has no effect on val/test splits.
        keypoint_flip_pairs: Keypoint left/right swap pairs, or ``None`` for a
            detection-only pipeline.  On the torchvision-native default backend
            (``aug_config=None``), an empty list disables ``RandomHorizontalFlip``
            entirely instead of applying it without relabelling â€” mirroring
            ``AlbumentationsWrapper.from_config``'s existing gating for the same
            sentinel.

    Returns:
        A ``Compose`` object containing the composed image transforms appropriate for the specified ``image_set``.
    r¯   z:Using multi-scale training with square resize and scales: r¢  r¥  Tr�  r¦  r§  s               r(   Ú"make_coco_transforms_square_div_64rª  ±  sª   € ð@ ˆ\€FØð [å+¨J¸ÈÐU`ÑaÔaˆØð 	"Ø˜R”j�\ˆFÝ�ŠÐYÐQWÐYÐYÑZÔZÐZàÐ=Ð=Ð=ÝÐ/ IÐ/Ð/Ñ0Ô0Ð0åØØØØØØ!Ø'Ø/ð	ñ 	ô 	ð 	r*   Úargsc                óˆ  — t          t          |dd¦  «        p|j        ¦  «        }|                     ¦   «         s1t                               d|› d�¦  «         t          d|› d�¦  «        ‚t          j        |j	        ¦  «        }t          |dd¦  «        }|rdnd}|d	z  |d
z  |› d�z  f|dz  |d
z  |› d�z  f|dz  |d
z  dz  fdœ}||  
                    dd¬¦  «        d                  \  }}	|j        }
|j        }|}t          |dg ¦  «        }t          |dd¦  «        }t          |dd¦  «        }t          ||¬¦  «        }t          |dd¦  «        }t          |¦  «        }|dk    r*|t          j        k    rt                               d¦  «         t%          |¦  «        }t'          | ||t          j        u|j        |j        |j        ||¬¦  «        }|
rwt                               d| › d |› �¦  «         t3          ||	t5          | ||t          j        u|j        |t          j        u|j        |j        ||||¬!¦  «        |||||¬"¦  «        }nvt                               d| › d#|› �¦  «         t3          ||	t9          | ||t          j        u|j        |t          j        u|j        |j        ||||¬!¦  «        |||||¬"¦  «        }|S )$aQ  Build a COCO dataset from an explicit configuration namespace.

    Direct callers must provide either ``dataset_dir`` or ``coco_path``, plus
    ``square_resize_div_64``, ``segmentation_head``, ``multi_scale``,
    ``expanded_scales``, ``patch_size``, and ``num_windows`` on ``args``. Keypoint, custom augmentation, scale-jitter,
    and augmentation-backend fields are optional.

    Args:
        image_set: COCO split identifier.
        args: Dataset, model, and transform configuration namespace.
        resolution: Target image resolution in pixels.

    Returns:
        The configured COCO dataset.

    Raises:
        AttributeError: If a required dataset or transform option is absent.
        FileNotFoundError: If the configured COCO root does not exist.
        KeyError: If ``image_set`` does not map to a supported COCO split.
    r    Nz
COCO path ú does not existÚuse_grouppose_keypointsFÚperson_keypointsÚ	instancesÚ	train2017r   z_train2017.jsonÚval2017z_val2017.jsonÚtest2017zimage_info_test-dev2017.json©r%   r£  r¤  Ú_r’   ©Úmaxsplitr   rˆ   rƒ  rÂ   T©r  Úaugmentation_backendÚcpuÚautoz­augmentation_backend='auto' resolved to torchvision because CUDA/Albumentations/kornia are unavailable; disabling GPU postprocess transforms and retaining CPU normalization.rÀ   zBuilding COCO ú* dataset with square resize at resolution ©	rÁ   r©   rŸ  rª   r«   rƒ  rÂ   r…  r†  )r  rÃ   r  rˆ   r  r  ú dataset at resolution )r   ÚgetattrÚ	coco_pathr'   rr   ÚerrorÚFileNotFoundErrorr   Ú
from_valuerÁ   ÚsplitÚsquare_resize_div_64Úsegmentation_headr   r   r   ÚTVrs   r   rÈ   ÚOFFr©   rª   r«   r  rÿ   rª  Ú
PER_SAMPLEr¨  )rÄ   r«  r¨   r   rÁ   Úhas_keypointsÚmodeÚPATHSr   r  rÅ  rÃ   r  rˆ   rƒ  rÂ   r†  r¹  Úresolved_augmentation_backendr…  r  Údatasets                         r(   Ú
build_cocorÏ    s  € õ* •˜˜m¨TÑ2Ô2ÐD°d´nÑEÔE€DØ�;Š;‰=Œ=ð DÝ�ŠÐ7 $Ð7Ð7Ð7Ñ8Ô8Ð8ÝÐ B¨TÐ BÐ BÐ BÑCÔCÐCÝÔ'¨Ô(8Ñ9Ô9€Kõ ˜DÐ";¸UÑCÔC€MØ!.Ð?ÐÐ°K€Dà˜Ñ$ d¨]Ñ&:ÀÐ=UÐ=UÐ=UÑ&UÐVØ�yÑ  $¨Ñ"6¸DÐ9OÐ9OÐ9OÑ"OÐPØ˜
Ñ" D¨=Ñ$8Ð;YÑ$YÐZðð €Eð ! §¢°¸q Ñ!AÔ!AÀ!Ô!DÔEÑ€J�ð  Ô4ÐØÔ*€MØ%ÐÝ% dÐ,EÀrÑJÔJÐÝ˜˜|¨TÑ2Ô2€JÝ˜4 °Ñ6Ô6€LÝ5°dÐN_Ð`Ñ`Ô`ÐÝ" 4Ð)?ÀÑGÔGÐÝ$=Ð>RÑ$SÔ$SÐ!ð ˜vÒ%Ð%Ð*GÕK^ÔKaÒ*aÐ*aÝ�Šðañ	
ô 	
ð 	
õ )Ð)FÑGÔG€OÝ*ØØØ¥z¤~Ð5ØÔ,Ø”?ØÔ$Ø!Ø#ð	ñ 	ô 	€Jð ð 5
Ý�ŠÐf YÐfÐfÐZdÐfÐfÑgÔgÐgÝØØÝ9ØØØ'­z¬~Ð=Ø $Ô 4Ø#.µjÔ6KÐ#KØœ?Ø Ô,Ø%Ø)Ø /Ø$7ðñ ô ð (Ø/Ø$;ð  1Ø!ð/
ñ 
ô 
ˆˆõ4 	�ŠÐS YÐSÐSÀzÐSÐSÑTÔTÐTÝØØÝ+ØØØ'­z¬~Ð=Ø $Ô 4Ø#.µjÔ6KÐ#KØœ?Ø Ô,Ø%Ø)Ø /Ø$7ðñ ô ð (Ø/Ø$;ð  1Ø!ð/
ñ 
ô 
ˆð2 €Nr*   c                óð  — t          |j        ¦  «        }|                     ¦   «         s1t                               d|› d�¦  «         t          d|› d�¦  «        ‚|dz  |dz  dz  f|dz  |dz  dz  f|dz  |dz  dz  fdœ}|                      dd	¬
¦  «        d         }||         \  }}|j        }|j        }	t          j
        |j        ¦  «        }
|j        }|j        }|j        }t          |dd¦  «        }t          |dg ¦  «        }t!          ||¬¦  «        }t          |dd¦  «        }t          |dd¦  «        }t#          t          |dd¦  «        ¦  «        }t%          |¦  «        }|dk    s|rdnt'          |¦  «        }t)          | ||
t          j        u|||||	¬¦  «        }|rit                               d| › d|› �¦  «         t/          ||t1          | ||
t          j        u||
t          j        u||||||¬¦  «        |	||d||¬¦	  «	        }nht                               d| › d|› �¦  «         t/          ||t5          | ||
t          j        u||
t          j        u||||||¬¦  «        |	||d||¬¦	  «	        }|S )aè  Build a Roboflow COCO-format dataset.

    This uses Roboflow's standard directory structure (train/valid/test folders with _annotations.coco.json).

    Each split is built by its own call, so label indices are taken from the train split for every non-train split (see
    :func:`_train_split_cat2label`). Letting a split derive its own mapping would shift its label indices whenever its
    annotation coverage of a grouping category differs from the train split's.

    Direct callers must provide ``dataset_dir``, ``square_resize_div_64``,
    ``segmentation_head``, ``multi_scale``, ``expanded_scales``,
    ``patch_size``, and ``num_windows`` on
    ``args``. Keypoint, custom augmentation, scale-jitter, and
    augmentation-backend fields are optional.

    Args:
        image_set: Roboflow split identifier.
        args: Dataset, model, and transform configuration namespace.
        resolution: Target image resolution in pixels.

    Returns:
        The configured Roboflow COCO-format dataset.

    Raises:
        AttributeError: If a required dataset or transform option is absent.
        FileNotFoundError: If the configured dataset root does not exist.
        KeyError: If ``image_set`` does not map to a supported Roboflow split.
    zRoboflow dataset path r­  r%   r&   Úvalidr¤  r´  rµ  r’   r¶  r   r®  Frˆ   r¸  rƒ  NrÂ   Tr¹  rº  rÀ   zBuilding Roboflow r¼  r½  )r  rÃ   r  rˆ   r  r£   r  r¾  )r   r    r'   rr   rÁ  rÂ  rÄ  rÅ  rÆ  r   rÃ  rÁ   r©   rª   r«   r¿  r   r   r   rx   rÈ   rÈ  r  rÿ   rª  rÉ  r¨  )rÄ   r«  r¨   r   rÌ  rÄ  r   r  rÅ  rÃ   rÁ   r©   rª   r«   r  rˆ   r†  rƒ  rÂ   rÍ  r…  r£   r  rÎ  s                           r(   Úbuild_roboflow_from_cocorÒ  ‡  s.  € õ8 �Ô Ñ!Ô!€DØ�;Š;‰=Œ=ð PÝ�ŠÐC¨dÐCÐCÐCÑDÔDÐDÝÐ N¸Ð NÐ NÐ NÑOÔOÐOð ˜‘. $¨¡.Ð3KÑ"KÐLØ�w‘  w¡Ð1IÑ IÐJØ˜‘  v¡Ð0HÑ HÐIðð €Eð �OŠO˜C¨!ˆOÑ,Ô,¨QÔ/€EØ  œ<Ñ€J�ð  Ô4ÐØÔ*€MÝÔ'¨Ô(8Ñ9Ô9€KØÔ*€OØ”€JØÔ"€Kå Ð&?ÀÑGÔGÐÝ% dÐ,EÀrÑJÔJÐÝ5°dÐN_Ð`Ñ`Ô`ÐÝ˜˜|¨TÑ2Ô2€JÝ˜4 °Ñ6Ô6€LÝ$=½gÀdÐLbÐdiÑ>jÔ>jÑ$kÔ$kÐ!Ý(Ð)FÑGÔG€Oð  Ò(Ð(Ð,=Ð(��ÕCYÐZ^ÑC_ÔC_€IÝ*ØØØ¥z¤~Ð5Ø'ØØØ!Ø#ð	ñ 	ô 	€Jð ð 1
Ý�ŠÐj¨ÐjÐjÐ^hÐjÐjÑkÔkÐkÝØØÝ9ØØØ'­z¬~Ð=Ø /Ø#.µjÔ6KÐ#KØ%Ø'Ø%Ø)Ø /Ø$7ðñ ô ð (Ø/Ø$;Ø#ØØ!ð+
ñ 
ô 
ˆˆõ0 	�ŠÐW¨ÐWÐWÈ:ÐWÐWÑXÔXÐXÝØØÝ+ØØØ'­z¬~Ð=Ø /Ø#.µjÔ6KÐ#KØ%Ø'Ø%Ø)Ø /Ø$7ðñ ô ð (Ø/Ø$;Ø#ØØ!ð+
ñ 
ô 
ˆð. €Nr*   )r    r!   r"   r#   )r/   r0   r"   r1   )r?   r0   r"   r!   )r?   r0   r"   rG   r�   )rL   rM   rN   rO   r"   rM   )rd   r   r"   re   )ry   r   r"   rz   )ry   r   rˆ   r‰   r"   rŠ   )Fr¦   r§   )
r¨   r7   r©   r#   rª   r7   r«   r7   r"   rz   )rÄ   r!   r¨   r7   rÁ   r#   r©   r#   rª   r7   r«   r7   rÂ   r#   rÃ   r#   r"   rG   )r:   r0   rÉ   rÊ   rË   rÊ   r"   r0   )rÏ   r   r"   r#   )rã   rä   rÝ   r7   rÜ   r7   r"   r   )
r½   rz   r[  r#   rZ  rG   rÂ   r#   r"   rM   )
r½   rr  r[  r#   rZ  rs  rÂ   r#   r"   rt  )rÄ   r!   r¨   r7   r½   rr  r[  r#   rƒ  r„  rÂ   r#   r…  r#   r†  r‡  r"   r   )	FFFr¦   r§   NTFN)rÄ   r!   r¨   r7   rÁ   r#   r©   r#   rŸ  r#   rª   r7   r«   r7   rƒ  r   rÂ   r#   r…  r#   r†  r‰   r"   r   )rÄ   r!   r«  r   r¨   r7   r"   rÿ   )Mr0  Ú
__future__r   rn   Úpathlibr   Útypingr   r   r   r   r	   rí   Útorch.utils.dataÚtorchvisionÚPILr
   r   Útorchvision.transforms.v2r   r   Úrfdetr.configr   r   Úrfdetr.datasets._aug_utilsr   r   Úrfdetr.datasets._torchvisionr   r   r   r   r   r   r   Úrfdetr.datasets.aug_configsr   Úrfdetr.datasets.io_utilsr   Ú!rfdetr.datasets.kornia_transformsr   r   Úrfdetr.datasets.transformsr   r   Úrfdetr.utilities.loggerr   rr   rl  r)   Ú	frozensetr.   Ú__annotations__r>   rF   rK   rc   rx   r‡   r¥   r¿   rÈ   rÞ   rØ   rý   Údatasetsrÿ   r  rq  r‚  r“  r›  rž  r¨  rª  rÏ  rÒ  rX   r*   r(   ú<module>rå     sA  ððð ð ð
 #Ð "Ð "Ð "Ð "Ð "à €€€Ø Ð Ð Ð Ð Ð Ø 2Ð 2Ð 2Ð 2Ð 2Ð 2Ð 2Ð 2Ð 2Ð 2Ð 2Ð 2Ð 2Ð 2à €€€Ø Ð Ð Ð Ø Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø 6Ð 6Ð 6Ð 6Ð 6Ð 6Ð 6Ð 6à 9Ð 9Ð 9Ð 9Ð 9Ð 9Ð 9Ð 9Ø aÐ aÐ aÐ aÐ aÐ aÐ aÐ aðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð 3Ð 2Ð 2Ð 2Ð 2Ð 2Ø 1Ð 1Ð 1Ð 1Ð 1Ð 1Ø [Ð [Ð [Ð [Ð [Ð [Ð [Ð [Ø GÐ GÐ GÐ GÐ GÐ GÐ GÐ GØ .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€à€ðMð Mð Mð Mð
 6?°YÐ?YÐ?YÐ?YÑ5ZÔ5ZÐ Ð ZÐ ZÐ ZÑ Zð_ð _ð _ð _ð$ð ð ð ðð ð ð ð &*ðGð Gð Gð Gð GðTð ð ð ðD ð  ð  ð  ð5ð 5ð 5ð 5ðt "ØØð	ð ð ð ð ð* Ø!ØØØØð6Pð 6Pð 6Pð 6Pð 6Pð 6Pðr*ð *ð *ð *ðZbð bð bð bð 4%ð 4%ð 4%ð 4%ðnAð Að Að Að A�KÔ(Ô6ñ Aô Að AðHOð Oð Oð Oð Oñ Oô Oð Oðl  Øða=ð a=ð a=ð a=ð a=ð a=ðP #Øð2*ð 2*ð 2*ð 2*ð 2*ð 2*ðx ðAFð AFð AFð AFð AFð AFðV ðGið Gið Gið Gið Gið Giðb ð0ð 0ð 0ð 0ð 0ð 0ðl Ø!Ø$ØØØ37ØØ!Ø,0ðjð jð jð jð jð` Ø!Ø$ØØØ37ØØ!Ø,0ðTð Tð Tð Tð Tðn|ð |ð |ð |ð~zð zð zð zð zð zr*   