§
    ­¸jXB  ã                  ó  — d Z ddlmZ ddlZddlmZ ddlmZ ddlm	Z	 ddl
mZmZ ddlmZ  e¦   «         Zd	Zd
ZdZ ed¬¦  «         G d„ d¦  «        ¦   «         Z G d„ de¦  «        Z G d„ de¦  «        Zd d„Z	 	 d!d"d„Zd#d$d„ZdS )%a¶  Model weights abstraction and download system.

Provides forward-compatible pattern for model weights across rf-detr and rf-detr-plus packages. External packages (like
rf-detr-plus) should inherit from ModelWeightsBase to ensure compile-time interface compatibility.

Critical Strategic Decisions:
    1. **Standalone first**: Check local ModelWeights before lazy-importing external packages
    2. **Compile-time safety**: Inheritance-based compatibility via ModelWeightsBase
    3. **Clean abstraction**: Enum values ARE ModelWeightAsset dataclass instances
    4. **Backward compatible**: Legacy OPEN_SOURCE_MODELS dict maintained
    5. **Offline testable**: All I/O operations mockable

Download Priority Order:
    1. Local ModelWeights.from_filename() - rf-detr's built-in models
    2. rfdetr_plus.assets.ModelWeights.from_filename() - lazy import if not found locally
    3. PLATFORM_MODELS dict - legacy fallback for backward compatibility
é    )ÚannotationsN)Ú	dataclass)ÚEnum)Ú_IS_RFDETR_PLUS_AVAILABLE)Ú_download_fileÚ_validate_file_md5)Ú
get_loggerÚRF_HOMEÚROBOFLOW_HOMEz~/.roboflow/modelsT)Úfrozenc                  ó6   — e Zd ZU dZded<   ded<   dZded<   dS )ÚModelWeightAssetaŸ  Dataclass representing a model asset with download information.

    This is the standard format for model assets across rf-detr packages. Both rf-detr and rf-detr-plus should use this
    structure for compatibility.

    Attributes:
        filename: The local filename for the model weights
        url: The download URL
        md5_hash: The expected MD5 hash for integrity validation (None if not available)

    Example:
        >>> asset = ModelWeightAsset(
        ...     filename='rf-detr-base.pth',
        ...     url='https://storage.googleapis.com/rfdetr/rf-detr-base-coco.pth',
        ...     md5_hash='b4d3ce46099eaed50626ede388caf979'
        ... )
    ÚstrÚfilenameÚurlNú
str | NoneÚmd5_hash)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   © ó    úk/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/assets/model_weights.pyr   r   )   sA   € € € € € € ðð ð$ €M€M�MØ€H€H�HØ€HÐÐÐÑÐÐr   r   c                  óÎ   — e Zd ZU dZded<   dd„Zedd„¦   «         Zedd	„¦   «         Zedd„¦   «         Z	e
dd„¦   «         Ze
dd„¦   «         Ze
dd„¦   «         Ze
dd„¦   «         ZdS )ÚModelWeightsBasea—  Base class for model weight registries.

    This base class ensures compile-time compatibility between rf-detr and rf-detr-plus. Both packages should inherit
    from this class to ensure they have the same interface.

    Each enum member's value must be a ModelWeightAsset instance.

    Example inheritance:
        >>> from rfdetr.assets import ModelWeightAsset
        >>> class MyModelWeights(ModelWeightsBase):
        ...     MODEL_NAME = ModelWeightAsset(
        ...         "model.pth",
        ...         "https://example.com/model.pth",
        ...         "abc123"
        ...     )

    Example usage:
        >>> from rfdetr.assets.model_weights import ModelWeights
        >>> asset = ModelWeights.from_filename("rf-detr-base.pth")
        >>> asset.filename
        'rf-detr-base.pth'
        >>> asset.url  # doctest: +SKIP
        'https://storage.googleapis.com/rfdetr/rf-detr-base-coco.pth'
    r   Ú_value_ÚassetÚreturnc                óH   — t                                | ¦  «        }||_        |S )N)ÚobjectÚ__new__r   )Úclsr   Úobjs      r   r#   zModelWeightsBase.__new__^   s   € Ý�nŠn˜SÑ!Ô!ˆØˆŒØˆ
r   r   c                ó   — | j         j        S )z6Get the filename from the underlying ModelWeightAsset.©r   r   ©Úselfs    r   r   zModelWeightsBase.filenamed   ó   € ð Œ|Ô$Ð$r   c                ó   — | j         j        S )z1Get the URL from the underlying ModelWeightAsset.)r   r   r(   s    r   r   zModelWeightsBase.urli   s   € ð Œ|ÔÐr   r   c                ó   — | j         j        S )z6Get the MD5 hash from the underlying ModelWeightAsset.)r   r   r(   s    r   r   zModelWeightsBase.md5_hashn   r*   r   r   úModelWeightAsset | Nonec                óB   — | D ]}|j         j        |k    r	|j         c S ŒdS )a‹  Get ModelWeightAsset by filename.

        Args:
            filename: The model filename (e.g., 'rf-detr-base.pth')

        Returns:
            ModelWeightAsset instance if found, None otherwise

        Example:
            >>> asset = ModelWeights.from_filename('rf-detr-base.pth')
            >>> asset.url
            'https://storage.googleapis.com/rfdetr/rf-detr-base-coco.pth'
        Nr'   )r$   r   Úmembers      r   Úfrom_filenamezModelWeightsBase.from_filenames   s;   € ð ð 	&ð 	&ˆFØŒ~Ô&¨(Ò2Ð2Ø”~Ð%Ð%Ð%ð 3àˆtr   c                óB   — |                       |¦  «        }|r|j        ndS )z¬Get download URL for a model by filename.

        Args:
            filename: The model filename

        Returns:
            URL string if found, None otherwise
        N)r0   r   ©r$   r   r   s      r   Úget_urlzModelWeightsBase.get_url‡   s(   € ð ×!Ò! (Ñ+Ô+ˆØ!Ð+ˆuŒyˆy tÐ+r   c                óB   — |                       |¦  «        }|r|j        ndS )zºGet expected MD5 hash for a model by filename.

        Args:
            filename: The model filename

        Returns:
            MD5 hash string if available, None otherwise
        N)r0   r   r2   s      r   Úget_md5zModelWeightsBase.get_md5”   s(   € ð ×!Ò! (Ñ+Ô+ˆØ!&Ð0ˆuŒ~ˆ~¨DÐ0r   ú	list[str]c                ó   — d„ | D ¦   «         S )zbList all available model filenames.

        Returns:
            List of model filenames
        c                ó&   — g | ]}|j         j        ‘ŒS r   r'   )Ú.0r/   s     r   ú
<listcomp>z0ModelWeightsBase.list_models.<locals>.<listcomp>¨   s   € Ð:Ð:Ð:¨F�”Ô'Ð:Ð:Ð:r   r   )r$   s    r   Úlist_modelszModelWeightsBase.list_models¡   s   € ð ;Ð:°cÐ:Ñ:Ô:Ð:r   N)r   r   r    r   ©r    r   )r    r   )r   r   r    r-   )r   r   r    r   )r    r6   )r   r   r   r   r   r#   Úpropertyr   r   r   Úclassmethodr0   r3   r5   r;   r   r   r   r   r   B   s"  € € € € € € ðð ð2 ÐÐÑðð ð ð ð ð%ð %ð %ñ „Xð%ð ð ð  ð  ñ „Xð ð ð%ð %ð %ñ „Xð%ð ðð ð ñ „[ðð& ð
,ð 
,ð 
,ñ „[ð
,ð ð
1ð 
1ð 
1ñ „[ð
1ð ð;ð ;ð ;ñ „[ð;ð ;ð ;r   r   c                  ó²  — e Zd ZdZ eddd¦  «        Z eddd¦  «        Z edd	d
¦  «        Z eddd¦  «        Z eddd¦  «        Z	 eddd¦  «        Z
 eddd¦  «        Z eddd¦  «        Z eddd¦  «        Z eddd¦  «        Z ed d!d"¦  «        Z ed#d$d%¦  «        Z ed&d'd(¦  «        Z ed)d*d+¦  «        Z ed,d-d.¦  «        Z ed/d0d1¦  «        Zd2S )3ÚModelWeightsa-  Enumeration of available RF-DETR model assets.

    Inherits from ModelWeightsBase to ensure compatibility with rf-detr-plus.

    Each enum member's value is a ModelWeightAsset instance containing:
    - filename: The local filename for the model weights
    - url: The download URL
    - md5_hash: The expected MD5 hash for integrity validation

    Example:
        >>> asset = ModelWeights.RF_DETR_BASE
        >>> asset.filename
        'rf-detr-base.pth'
        >>> asset.url
        'https://storage.googleapis.com/rfdetr/rf-detr-base-coco.pth'
    zrf-detr-base.pthz;https://storage.googleapis.com/rfdetr/rf-detr-base-coco.pthÚ b4d3ce46099eaed50626ede388caf979zrf-detr-base-o365.pthz]https://storage.googleapis.com/rfdetr/top-secret-1234/lwdetr_dinov2_small_o365_checkpoint.pthÚ d93f4921ccbb0f0a2e4364bed290892bzrf-detr-base-2.pthz8https://storage.googleapis.com/rfdetr/rf-detr-base-2.pthÚ 462f4d9df407ddc1812f42614040e913zrf-detr-large.pthz7https://storage.googleapis.com/rfdetr/rf-detr-large.pthÚ 992c8e862aa733a7bb2777e45d49f1a0zrf-detr-large-2026.pthz<https://storage.googleapis.com/rfdetr/rf-detr-large-2026.pthÚ 5cb72153541cbcb9aa6efa26222acc75zrf-detr-nano.pthzKhttps://storage.googleapis.com/rfdetr/nano_coco/checkpoint_best_regular.pthÚ fb6504cce7fbdc783f7a46991f07639fzrf-detr-small.pthzLhttps://storage.googleapis.com/rfdetr/small_coco/checkpoint_best_regular.pthÚ fb37061c1af7bace359c91b723a8d5c1zrf-detr-medium.pthzMhttps://storage.googleapis.com/rfdetr/medium_coco/checkpoint_best_regular.pthÚ 7223f764a87b863f02eb8d52bf0ce2eez#rf-detr-keypoint-preview-xlarge.pthzIhttps://storage.googleapis.com/rfdetr/rf-detr-keypoint-preview-xlarge.pthÚ 6de511943ee85a547d4c5cb527daf0ebzrf-detr-seg-preview.ptz<https://storage.googleapis.com/rfdetr/rf-detr-seg-preview.ptÚ e35820c28fb86080558123e47a5e49cazrf-detr-seg-nano.ptz:https://storage.googleapis.com/rfdetr/rf-detr-seg-n-ft.pthÚ 9995497791d0ff1664a1d9ddee9cfd20zrf-detr-seg-small.ptz:https://storage.googleapis.com/rfdetr/rf-detr-seg-s-ft.pthÚ 0a2a3006381d0c42853907e700eadd08zrf-detr-seg-medium.ptz:https://storage.googleapis.com/rfdetr/rf-detr-seg-m-ft.pthÚ a49af1562c3719227ad43d0ca53b4c7azrf-detr-seg-large.ptz:https://storage.googleapis.com/rfdetr/rf-detr-seg-l-ft.pthÚ 275f7b094909544ed2841c94a677d07ezrf-detr-seg-xlarge.ptz;https://storage.googleapis.com/rfdetr/rf-detr-seg-xl-ft.pthÚ 3693b35d0eea86ebb3e0444f4a611fbazrf-detr-seg-xxlarge.ptz<https://storage.googleapis.com/rfdetr/rf-detr-seg-2xl-ft.pthÚ 040bc3412af840fa8a47e0ff69b552baN)r   r   r   r   r   ÚRF_DETR_BASEÚRF_DETR_BASE_O365ÚRF_DETR_BASE_2ÚRF_DETR_LARGEÚRF_DETR_LARGE_2026ÚRF_DETR_NANOÚRF_DETR_SMALLÚRF_DETR_MEDIUMÚRF_DETR_KEYPOINT_PREVIEWÚRF_DETR_SEG_PREVIEWÚRF_DETR_SEG_NANOÚRF_DETR_SEG_SMALLÚRF_DETR_SEG_MEDIUMÚRF_DETR_SEG_LARGEÚRF_DETR_SEG_XLARGEÚRF_DETR_SEG_XXLARGEr   r   r   r@   r@   «   sô  € € € € € ðð ð$ $Ð#ØØEØ*ñô €Lð
 )Ð(ØØgØ*ñô Ðð
 &Ð%ØØBØ*ñô €Nð
 %Ð$ØØAØ*ñô €Mð
 *Ð)Ø ØFØ*ñô Ðð
 $Ð#ØØUØ*ñô €Lð
 %Ð$ØØVØ*ñô €Mð
 &Ð%ØØWØ*ñô €Nð
  0Ð/Ø-ØSØ*ñ ô  Ðð +Ð*Ø ØFØ*ñô Ðð
 (Ð'ØØDØ*ñô Ðð
 )Ð(ØØDØ*ñô Ðð
 *Ð)ØØDØ*ñô Ðð
 )Ð(ØØDØ*ñô Ðð
 *Ð)ØØEØ*ñô Ðð
 +Ð*Ø ØFØ*ñô ÐÐÐr   r@   r    r   c                 ó  — t           j                             t          ¦  «        p*t           j                             t          ¦  «        pt
          } t           j                             t           j                             | ¦  «        ¦  «        S )us  Return the directory where RF-DETR caches downloaded model weights.

    Reads the ``RF_HOME`` environment variable, falling back to its alias ``ROBOFLOW_HOME``; defaults to
    ``~/.roboflow/models`` when neither is set.  ``RF_HOME`` is canonical â€” when both variables are set it wins, so
    existing configurations keep their behavior.  An empty value is treated as unset.

    Set either variable to override the cache location for all RF-DETR models:

    .. code-block:: bash

        export RF_HOME=/mnt/shared/models       # canonical
        export ROBOFLOW_HOME=/mnt/shared/models  # accepted alias

    Args: None

    Returns:
        Absolute, user-expanded path to the model cache directory.  The directory is *not* created by this function â€”
        callers that need it to exist should call ``os.makedirs(get_model_cache_dir(), exist_ok=True)`` themselves.

    Examples:
        >>> import os
        >>> _ = os.environ.pop("RF_HOME", None)  # ensure default
        >>> _ = os.environ.pop("ROBOFLOW_HOME", None)
        >>> expected = os.path.normpath(os.path.expanduser("~/.roboflow/models"))
        >>> get_model_cache_dir() == expected
        True
        >>> os.environ["RF_HOME"] = "~/rfdetr_cache"
        >>> expected = os.path.normpath(os.path.expanduser("~/rfdetr_cache"))
        >>> get_model_cache_dir() == expected
        True
        >>> del os.environ["RF_HOME"]
        >>> os.environ["ROBOFLOW_HOME"] = "~/roboflow_cache"
        >>> expected = os.path.normpath(os.path.expanduser("~/roboflow_cache"))
        >>> get_model_cache_dir() == expected
        True
        >>> del os.environ["ROBOFLOW_HOME"]
    )	ÚosÚenvironÚgetÚ_RF_HOME_ENV_VARÚ_ROBOFLOW_HOME_ENV_VARÚ_DEFAULT_CACHE_DIRÚpathÚabspathÚ
expanduser)Ú	cache_dirs    r   Úget_model_cache_dirrl     sW   € õP ”
—’Õ/Ñ0Ô0ÐpµB´J·N²NÕCYÑ4ZÔ4ZÐpÕ^p€IÝŒ7�?Š?�2œ7×-Ò-¨iÑ8Ô8Ñ9Ô9Ð9r   FÚpretrain_weightsÚ
redownloadÚboolÚvalidate_md5ÚNonec                óÚ  — d}t           j                             | ¦  «        }t                               |¦  «        }|€Et
          r>	 ddlm} |                     |¦  «        }n!# t          $ r}|j        dvr‚ Y d}~nd}~ww xY w|�|j	        }|r|j
        nd}n0	 ddlm}	 ||	vrdS |	|         }d}n# t          t          f$ r Y dS w xY wt           j                             | ¦  «        rU|sS|rO|rMt!          | |¦  «        st"                               d| › d�¦  «         nt"                               d| › d	�¦  «         dS t"                               d
| › �¦  «         t)          || |¬¦  «         dS )a  Download pretrained weights with optional MD5 validation.

    Download Priority Order:
        The function searches for models in the following order, stopping at the first match:

        1. **Local ModelWeights** (primary source):
           - Checks rf-detr's built-in ModelWeights enum
           - Ensures rf-detr works completely standalone
           - No unnecessary imports or performance overhead

        2. **External packages** (lazy import):
           - Only attempts import if model not found locally
           - Tries rf-detr-plus.assets.ModelWeights if installed
           - Gracefully handles missing packages (ImportError/AttributeError)

        3. **Legacy platform models** (backward compatibility):
           - Falls back to PLATFORM_MODELS dict for older models
           - Maintains compatibility with existing deployments
           - No MD5 validation for legacy models

    Args:
        pretrain_weights: Name of the pretrained weights file (e.g., 'rf-detr-base.pth')
        redownload: Force re-download even if file exists
        validate_md5: Whether to validate MD5 hash of downloaded file

    Example:
        >>> download_pretrain_weights('rf-detr-base.pth')  # doctest: +SKIP
        Downloading pretrained weights for rf-detr-base.pth
    Nr   )r@   >   úrfdetr_plus.assetsÚrfdetr_plus)ÚPLATFORM_MODELSzExisting file uÕ    has incorrect MD5 hash. It may be a user-provided checkpoint or a corrupted/tampered file â€” skipping re-download to avoid overwriting it. To force a fresh download of the original weights, pass redownload=True.zFile z& already exists with correct MD5 hash.z#Downloading pretrained weights for )r   r   Úexpected_md5)rb   rh   Úbasenamer@   r0   r   Úrfdetr_plus.assetsÚModuleNotFoundErrorÚnamer   r   Úrfdetr.platform.downloadsru   ÚImportErrorÚKeyErrorÚexistsr   ÚloggerÚwarningÚinfor   )
rm   rn   rp   r   Ú
model_nameÚPlusModelWeightsÚexr   rv   ru   s
             r   Údownload_pretrain_weightsr…   ?  s  € ðD &*€Eõ ”×!Ò!Ð"2Ñ3Ô3€Jõ ×&Ò& zÑ2Ô2€Eð €}Õ2€}ð	ØKÐKÐKÐKÐKÐKà$×2Ò2°:Ñ>Ô>ˆEˆEøÝ"ð 	ð 	ð 	ØŒwÐCÐCÐCØð DÐCÐCÐCÐCøøøøð	øøøð
 ÐØŒiˆØ)5Ð?�u”~�~¸4ˆˆð		ØAÐAÐAÐAÐAÐAà Ð0Ð0Ø�à! *Ô-ˆCØˆLˆLøÝ�XÐ&ð 	ð 	ð 	ØˆFˆFð	øøøõ 
„w‡~‚~Ð&Ñ'Ô'ð °
ð Øð 		^˜Lð 		^Ý%Ð&6¸ÑEÔEð ^Ý—’ð_Ð%5ð _ð _ð _ñô ð ð õ —’Ð\Ð$4Ð\Ð\Ð\Ñ]Ô]Ð]Øˆå
‡K‚KÐHÐ6FÐHÐHÑIÔIÐIÝØØ!Ø!ðñ ô ð ð ð s0   ÁA" Á"
B Á,
A;Á;B Â
B0 Â%
B0 Â0CÃCÚstrictc                ó  — t           j                             | ¦  «        s|rt          d| › �¦  «        ‚dS t           j                             | ¦  «        }t
                               |¦  «        }|�|j        € t           	                    d|› d�¦  «         dS t          | |j        ¦  «        s6d| › d|› d	�}|rt          |¦  «        ‚t                               |¦  «         dS t           	                    d
| › �¦  «         dS )a«  Validate MD5 hash of pretrained weights file.

    Args:
        pretrain_weights: Path to the pretrained weights file
        strict: If True, raise error on validation failure. If False, just warn.

    Returns:
        True if validation passes or no hash is available, False otherwise

    Raises:
        ValueError: If strict=True and validation fails
        FileNotFoundError: If strict=True and file doesn't exist
    z#Pretrained weights file not found: FNzNo MD5 hash available for z, skipping validationTzMD5 hash validation failed for zf. The file may be corrupted or tampered with. Consider re-downloading with download_pretrain_weights('z', redownload=True)zMD5 validation passed for )rb   rh   r~   ÚFileNotFoundErrorrw   r@   r0   r   r   Údebugr   Ú
ValueErrorr€   )rm   r†   r‚   r   Ú	error_msgs        r   Úvalidate_pretrain_weightsrŒ   ›  s/  € õ Œ7�>Š>Ð*Ñ+Ô+ð Øð 	^Ý#Ð$\ÐJZÐ$\Ð$\Ñ]Ô]Ð]Øˆuõ ”×!Ò!Ð"2Ñ3Ô3€JÝ×&Ò& zÑ2Ô2€Eà€}˜œÐ.å�ŠÐS°*ÐSÐSÐSÑTÔTÐTØˆtåÐ.°´Ñ?Ô?ð 
ðgÐ.>ð gð gàGQðgð gð gð 	ð
 ð 	&Ý˜YÑ'Ô'Ð'å�NŠN˜9Ñ%Ô%Ð%Øˆuå
‡L‚LÐ@Ð.>Ð@Ð@ÑAÔAÐAØˆ4r   r<   )FT)rm   r   rn   ro   rp   ro   r    rq   )F)rm   r   r†   ro   r    ro   )r   Ú
__future__r   rb   Údataclassesr   Úenumr   Úrfdetr.platformr   Úrfdetr.utilities.filesr   r   Úrfdetr.utilities.loggerr	   r   re   rf   rg   r   r   r@   rl   r…   rŒ   r   r   r   ú<module>r“      s±  ððð ð$ #Ð "Ð "Ð "Ð "Ð "à 	€	€	€	Ø !Ð !Ð !Ð !Ð !Ð !Ø Ð Ð Ð Ð Ð à 5Ð 5Ð 5Ð 5Ð 5Ð 5Ø EÐ EÐ EÐ EÐ EÐ EÐ EÐ EØ .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€àÐ Ø(Ð Ø)Ð ð €�$ÐÑÔð ð  ð  ð  ð  ñ  ô  ñ Ôð ð0f;ð f;ð f;ð f;ð f;�tñ f;ô f;ð f;ðRdð dð dð dð dÐ#ñ dô dð dðP):ð ):ð ):ð ):ð\ ØðYð Yð Yð Yð Yðx)ð )ð )ð )ð )ð )ð )r   