Ë
    Fêñiæ$  ã                  óf  — 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
 ddlZddlZddlZddlmZ ej"                  Zej&                  fdd	„Zej*                  Zd
ad„ Zee_        ej&                  fdd„Zddd„Zdd„Zej6                  Zd„ Zd„ Zeddd„«       Zed„ «       Z eddd„«       Z!y)zDMonkey patches to update/extend functionality of existing functions.é    )ÚannotationsN)Úcontextmanager)Úcopy)ÚPath)ÚAny)ÚImagec                óî  — t        j                  | t         j                  «      }| j                  d«      rft	        j
                  |t        j                  «      \  }}|r<t        |«      dk(  r|d   j                  dk(  r|d   S t        j                  |d¬«      S yt	        j                  ||«      }|€+| j                  «       j                  d«      rt        | |«      }|�|j                  dk(  r|d	   S |S )
aÆ  Read an image from a file with multilanguage filename support.

    Args:
        filename (str): Path to the file to read.
        flags (int, optional): Flag that can take values of cv2.IMREAD_*. Controls how the image is read.

    Returns:
        (np.ndarray | None): The read image array, or None if reading fails.

    Examples:
        >>> img = imread("path/to/image.jpg")
        >>> img = imread("path/to/image.jpg", cv2.IMREAD_GRAYSCALE)
    )z.tiffz.tifé   r   é   é   )ÚaxisN)z.avifz.heic).N)ÚnpÚfromfileÚuint8ÚendswithÚcv2ÚimdecodemultiÚIMREAD_UNCHANGEDÚlenÚndimÚstackÚimdecodeÚlowerÚ_imread_pil)ÚfilenameÚflagsÚ
file_bytesÚsuccessÚframesÚims         ú[/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/utils/patches.pyÚimreadr"      sÒ   € ô —‘˜X¤r§x¡xÓ0€JØ×ÑÐ*Ô+Ü×+Ñ+¨J¼×8LÑ8LÓM‰ˆ�Ùä # F£¨qÒ 0°V¸A±Y·^±^ÀqÒ5H�6˜!‘9ÐfÌbÏhÉhÐW]ÐdeÔNfÐfØä�\‰\˜* eÓ,ˆàˆ:˜(Ÿ.™.Ó*×3Ñ3Ð4FÔGÜ˜X uÓ-ˆBØ " °2·7±7¸a²<ˆr�)‰}ÐGÀRÐGó    Fc                óÂ   — t         rt        | g|¢­i |¤ŽS 	 t        | g|¢­i |¤ŽS # t        $ r/ ddlm}  |d«       ddlm}  |«        da t        | g|¢­i |¤ŽcY S w xY w)at  Open an image with PIL, lazily registering the HEIF plugin on first failure.

    This monkey-patches PIL.Image.open to add HEIC/HEIF support via pi-heif (lightweight, decode-only), avoiding the
    ~800ms startup cost of importing the package unless actually needed. AVIF is supported natively by Pillow 12+ and
    does not require a plugin.

    Args:
        filename (str): Path to the image file.
        *args (Any): Additional positional arguments passed to PIL.Image.open.
        **kwargs (Any): Additional keyword arguments passed to PIL.Image.open.

    Returns:
        (PIL.Image.Image): The opened PIL image.
    r   )Úcheck_requirementszpi-heif)Úregister_heif_openerT)Ú_pil_plugins_registeredÚ_image_openÚ	ExceptionÚultralytics.utils.checksr%   Úpi_heifr&   )r   ÚargsÚkwargsr%   r&   s        r!   Ú
image_openr.   7   st   € õ  Ü˜8Ð5 dÒ5¨fÑ5Ð5ð
6Ü˜8Ð5 dÒ5¨fÑ5Ð5øÜò 6Ý?á˜9Ô%Ý0áÔØ"&ÐÜ˜8Ð5 dÒ5¨fÑ5Ò5ð6ús   —& ¦5AÁAc                ó„  — 	 t        j                  | «      5 }|t        j                  k(  r-t	        j
                  |j                  d«      «      cddd«       S t        j                  t	        j
                  |j                  d«      «      t        j                  «      cddd«       S # 1 sw Y   yxY w# t        $ r Y yw xY w)aP  Read an image using PIL as fallback for formats not supported by OpenCV.

    Args:
        filename (str): Path to the file to read.
        flags (int, optional): OpenCV imread flags (used to determine grayscale conversion).

    Returns:
        (np.ndarray | None): The read image array in BGR format, or None if reading fails.
    ÚLNÚRGB)
r   Úopenr   ÚIMREAD_GRAYSCALEr   ÚasarrayÚconvertÚcvtColorÚCOLOR_RGB2BGRr)   )r   r   Úimgs      r!   r   r   Y   s˜   € ðÜ�Z‰Z˜Ó!ð 	S SØœ×,Ñ,Ò,Ü—z‘z #§+¡+¨cÓ"2Ó3÷	Sñ 	Sô —<‘<¤§
¡
¨3¯;©;°uÓ+=Ó >Ä×@QÑ@QÓR÷	S÷ 	Sò 	Sûô ò Ùðús;   ‚B3 —7B'Á	B3 ÁAB'Â	B3 Â'B0Â,B3 Â0B3 Â3	B?Â>B?c                óœ   — 	 t        j                  t        | «      j                  ||«      d   j	                  | «       y# t
        $ r Y yw xY w)aD  Write an image to a file with multilanguage filename support.

    Args:
        filename (str): Path to the file to write.
        img (np.ndarray): Image to write.
        params (list[int], optional): Additional parameters for image encoding.

    Returns:
        (bool): True if the file was written successfully, False otherwise.

    Examples:
        >>> import numpy as np
        >>> img = np.zeros((100, 100, 3), dtype=np.uint8)  # Create a black image
        >>> success = imwrite("output.jpg", img)  # Write image to file
        >>> print(success)
        True
    r
   TF)r   Úimencoder   ÚsuffixÚtofiler)   )r   r8   Úparamss      r!   Úimwriter>   l   sF   € ð$Ü�‰”T˜(“^×*Ñ*¨C°Ó8¸Ñ;×BÑBÀ8ÔLØøÜò Ùðús   ‚<? ¿	AÁ
Ac                óV   — t        | j                  d«      j                  «       |«       y)a8  Display an image in the specified window with multilanguage window name support.

    This function is a wrapper around OpenCV's imshow function that displays an image in a named window. It handles
    multilanguage window names by encoding them properly for OpenCV compatibility.

    Args:
        winname (str): Name of the window where the image will be displayed. If a window with this name already exists,
            the image will be displayed in that window.
        mat (np.ndarray): Image to be shown. Should be a valid numpy array representing an image.

    Examples:
        >>> import numpy as np
        >>> img = np.zeros((300, 300, 3), dtype=np.uint8)  # Create a black image
        >>> img[:100, :100] = [255, 0, 0]  # Add a blue square
        >>> imshow("Example Window", img)  # Display the image
    Úunicode_escapeN)Ú_imshowÚencodeÚdecode)ÚwinnameÚmats     r!   ÚimshowrF   …   s!   € ô" ˆG�N‰NÐ+Ó,×3Ñ3Ó5°sÕ;r#   c                 óN   — ddl m} |r	d|vrd|d<   t        j                  | i |¤ŽS )aD  Load a PyTorch model with updated arguments to avoid warnings.

    This function wraps torch.load and adds the 'weights_only' argument for PyTorch 1.13.0+ to prevent warnings.

    Args:
        *args (Any): Variable length argument list to pass to torch.load.
        **kwargs (Any): Arbitrary keyword arguments to pass to torch.load.

    Returns:
        (Any): The loaded PyTorch object.

    Notes:
        For PyTorch versions 1.13 and above, this function automatically sets `weights_only=False` if the argument is
        not provided, to avoid deprecation warnings.
    r   )Ú
TORCH_1_13Úweights_onlyF)Úultralytics.utils.torch_utilsrH   ÚtorchÚload)r,   r-   rH   s      r!   Ú
torch_loadrM   �   s/   € õ  9á�n¨FÑ2Ø!&ˆˆ~Ñä�:‰:�tÐ&˜vÑ&Ð&r#   c                 ó®   — t        d«      D ]  }	 t        | i |¤Žc S  y# t        $ r,}|dk(  r|‚t        j                  d|z  dz  «       Y d}~ŒCd}~ww xY w)aê  Save PyTorch objects with retry mechanism for robustness.

    This function wraps torch.save with 3 retries and exponential backoff in case of save failures, which can occur due
    to device flushing delays or antivirus scanning.

    Args:
        *args (Any): Positional arguments to pass to torch.save.
        **kwargs (Any): Keyword arguments to pass to torch.save.

    Examples:
        >>> model = torch.nn.Linear(10, 1)
        >>> torch_save(model.state_dict(), "model.pt")
    é   r   r   N)ÚrangeÚ_torch_saveÚRuntimeErrorÚtimeÚsleep)r,   r-   ÚiÚes       r!   Ú
torch_saverW   µ   sa   € ô �1‹Xò #ˆð	#Ü Ð/¨Ñ/Ò/ñ#øô ò 	#Ø�AŠvØ�Ü�J‰J˜˜1™ ‘z×"Ñ"ûð	#ús   �
Ÿ	A¨"AÁAc              #  óŽ   ‡K  — | r:|r8|dk(  r3t         j                  Šddœˆfd„
}|t         _        d–— ‰t         _        yd–— y­w)zwWorkaround for ONNX torch.arange incompatibility with FP16.

    https://github.com/pytorch/pytorch/issues/148041.
    ÚonnxN)Údtypec                ó2   •—  ‰|i |¤Žj                  | «      S )zNWrap torch.arange to cast dtype after creation instead of passing it directly.)Úto)rZ   r,   r-   Úfuncs      €r!   Úarangezarange_patch.<locals>.arangeÕ   s   ø€ á˜Ð( Ñ(×+Ñ+¨EÓ2Ð2r#   )rK   r^   )ÚdynamicÚhalfÚfmtr^   r]   s       @r!   Úarange_patchrb   Ì   s;   øè ø€ ñ ‘4˜C 6šMÜ�|‰|ˆà $ö 	3ð ŒŒÛØŒ�äùs   ƒAAc               #  óÂ   ‡K  — ddl m}  | rNt        j                  j                  Šˆfd„}|t        j                  _        d–— ‰t        j                  _        yd–— y­w)zFWorkaround for ONNX export issues in PyTorch 2.9+ with Dynamo enabled.r   )Ú	TORCH_2_9c                 ó   •—  ‰| i |¤ddi¤ŽS )zCExport model to ONNX format with Dynamo disabled for compatibility.ÚdynamoF© )r,   r-   r]   s     €r!   Útorch_exportz'onnx_export_patch.<locals>.torch_exportè   s   ø€ á˜Ð6 Ñ6°Ò6Ð6r#   N)rJ   rd   rK   rY   Úexport)rd   rh   r]   s     @r!   Úonnx_export_patchrj   à   sC   øè ø€ õ 8áÜ�z‰z× Ñ ˆô	7ð )Œ�
‰
ÔÛØ Œ�
‰
Õäùs   ƒAAc              #  ó"  K  — |r[t        | «      }|j                  «       D ]  \  }}t        | ||«       Œ 	 | –— | j                  j	                  |j                  «       y| –— y# | j                  j	                  |j                  «       w xY w­w)aF  Context manager to temporarily override configurations in args.

    Args:
        args (IterableSimpleNamespace): Original configuration arguments.
        overrides (dict[str, Any] | None): Dictionary of overrides to apply.

    Yields:
        (IterableSimpleNamespace): Configuration arguments with overrides applied.
    N)r   ÚitemsÚsetattrÚ__dict__Úupdate)r,   Ú	overridesÚoriginal_argsÚkeyÚvalues        r!   Úoverride_configsrt   ó   s|   è ø€ ñ Ü˜T›
ˆØ#Ÿ/™/Ó+ò 	&‰JˆC�Ü�D˜#˜uÕ%ð	&ð	9ØŠJà�M‰M× Ñ  ×!7Ñ!7Õ8à‹
øð �M‰M× Ñ  ×!7Ñ!7Õ8üs   ‚3B¶A% º+BÁ%'BÂB)r   Ústrr   ÚintÚreturnznp.ndarray | None)N)r   ru   r8   ú
np.ndarrayr=   zlist[int] | Nonerw   Úbool)rD   ru   rE   rx   rw   ÚNone)FFÚ )r_   ry   r`   ry   ra   ru   )rp   zdict[str, Any] | None)"Ú__doc__Ú
__future__r   rS   Ú
contextlibr   r   Úpathlibr   Útypingr   r   Únumpyr   rK   ÚPILr   rF   rA   ÚIMREAD_COLORr"   r2   r(   r'   r.   r   r>   ÚsaverQ   rM   rW   rb   rj   rt   rg   r#   r!   ú<module>r…      sÌ   ðá Jå "ã Ý %Ý Ý Ý ã 
Û Û Ý ð �*‰*€ð (+×'7Ñ'7ô Hð< �j‰j€ØÐ ò6ð> €„
ð -0×,<Ñ,<ô ô&ó2<ð* �j‰j€ò'ò0#ð. óó ðð& ñó ðð$ óó ñr#   