§
    ­¸jï  ã                  ót   — U d Z ddlmZ ddl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Zg Zded<   dd	œdd„ZdS )a  Safe checkpoint loading helpers.

This module provides :func:`_safe_torch_load`, a defense-in-depth wrapper around :func:`torch.load` that prevents
pickle-based remote code execution (CWE-502) when loading checkpoints from external or user-supplied sources.
é    )ÚannotationsN)ÚPath)ÚAnyz	list[str]Ú__all__F)ÚtrustÚpathú
str | Pathr   ÚboolÚreturnr   c               ó:  — 	 t          j        | dd¬¦  «        S # t          t          j        f$ r Y nw xY w	 t           j                             t          j        t          j
        g¦  «        5  t          j        | dd¬¦  «        cddd¦  «         S # 1 swxY w Y   n# t          t          j        f$ r Y nw xY w|rDt          j        dt          | ¦  «        ›d�t          d¬¦  «         t          j        | dd	¬¦  «        S t          d
t          | ¦  «        ›d�¦  «        ‚)u»  Load a PyTorch checkpoint as safely as possible.

    Tries progressively less restrictive deserialization strategies:

    1. ``weights_only=True`` (strict â€” only tensors and a small set of
       built-in scalars).
    2. Same as 1, but with ``argparse.Namespace`` and
       ``types.SimpleNamespace`` temporarily allowed via the
       :func:`torch.serialization.safe_globals` context manager so that legacy
       RF-DETR checkpoints that embed an ``args`` namespace can be loaded
       without falling back to pickle.  The allow-list is scoped to this call
       and does **not** permanently mutate global deserialization state.
    3. ``weights_only=False`` (full pickle) â€” allowed **only** when
       ``trust=True``, with a loud :class:`UserWarning`.  Never used for
       checkpoints received from external sources.

    Args:
        path: Path to the checkpoint file.
        trust: When ``True``, allow pickle deserialization as a last-resort
            fallback and emit a :class:`UserWarning`.  Set this only for
            checkpoint files produced by RF-DETR itself (e.g. during legacy
            checkpoint conversion) that may contain non-tensor Python
            objects that are not covered by the safe-globals list.

    Returns:
        The loaded checkpoint (usually a :class:`dict`).

    Raises:
        RuntimeError: When all safe loading strategies fail and
            ``trust=False``.  The error message suggests passing ``trust=True``
            (or ``trust_checkpoint=True`` at the ``RFDETR.from_checkpoint()``
            level) so the caller can make an informed decision.

    Examples:
        >>> import torch, tempfile, os
        >>> with tempfile.NamedTemporaryFile(suffix=".pth", delete=False) as fh:
        ...     path = fh.name
        >>> torch.save({"model": {"weight": torch.tensor([1.0])}}, path)
        >>> ckpt = _safe_torch_load(path)
        >>> list(ckpt.keys())
        ['model']
        >>> os.unlink(path)
    ÚcpuT)Úmap_locationÚweights_onlyNzLoading checkpoint zý with weights_only=False. This allows arbitrary Python objects to be deserialized from the checkpoint file, which can execute malicious code if the file comes from an untrusted source. Only use trust=True for checkpoint files produced by RF-DETR itself.é   )Ú
stacklevelFz!Failed to safely load checkpoint zë. The file likely contains custom Python objects that cannot be deserialized with weights_only=True. If you fully trust this checkpoint source, pass trust=True to _safe_torch_load() or trust_checkpoint=True to RFDETR.from_checkpoint().)ÚtorchÚloadÚRuntimeErrorÚpickleÚUnpicklingErrorÚserializationÚsafe_globalsÚargparseÚ	NamespaceÚtypesÚSimpleNamespaceÚwarningsÚwarnÚstrÚUserWarning)r   r   s     úc/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/utilities/io.pyÚ_safe_torch_loadr"      s³  € ðZÝŒz˜$¨UÀÐFÑFÔFÐFøÝ�&Ô0Ð1ð ð ð ØˆðøøøðÝÔ ×-Ò-­xÔ/AÅ5ÔCXÐ.YÑZÔZð 	Kð 	KÝ”:˜d°ÀTÐJÑJÔJð	Kð 	Kð 	Kð 	Kñ 	Kô 	Kð 	Kð 	Kð 	Kð 	Kð 	Kð 	Køøøð 	Kð 	Kð 	Kð 	Kð 	Køå�&Ô0Ð1ð ð ð Øˆðøøøð ð 
HÝŒðS¥# d¡)¤)ð Sð Sð Sõ
 Øð	
ñ 	
ô 	
ð 	
õ Œz˜$¨UÀÐGÑGÔGÐGå
ð	S­C°©I¬Ið 	Sð 	Sð 	Sñô ð sA   ‚ ™2±2¶5B Á+BÂB ÂBÂB ÂBÂB ÂB4Â3B4)r   r	   r   r
   r   r   )Ú__doc__Ú
__future__r   r   r   r   r   Úpathlibr   Útypingr   r   r   Ú__annotations__r"   © ó    r!   ú<module>r*      sÁ   ððð ð ð #Ð "Ð "Ð "Ð "Ð "à €€€Ø €€€Ø €€€Ø €€€Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à €€€ð €Ð Ð Ð Ñ ð 9>ð Rð Rð Rð Rð Rð Rð Rð Rr)   