§
    l¬¸já)  ã                  ób  — 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d	Zej        fd,d„Zej        Zdad„ Zee_        ej        fd-d„Zej        fd,d„Zd.d/d„Zd0d„Zej        Zd „ Zd!„ Z ed1d2d'„¦   «         Z!ed(„ ¦   «         Z"ed.d3d+„¦   «         Z#dS )4zDMonkey patches to update/extend functionality of existing functions.é    )ÚannotationsN)Úcontextmanager)Úcopy)ÚPath)ÚAny)ÚImage)z.avifz.heicz.heifÚfilenameú
str | PathÚflagsÚintÚreturnúnp.ndarray | Nonec                óÜ  — t          | ¦  «        } 	 t          j        | t          j        ¦  «        }n# t          t
          f$ r Y dS w xY w|j        sdS |t          j        k    r¢|  	                    ¦   «          
                    d¦  «        r{t          j        |t          j        ¦  «        \  }}|sdS t          |¦  «        dk    s|d         j        dk    r1t          |¦  «        dk    r|d         nt          j        |d¬¦  «        S t          j        ||¦  «        }|€<|  	                    ¦   «          
                    t"          ¦  «        rt%          | |¦  «        }|�|j        dk    r|d         n|S )	aÍ  Read an image from a file with multilanguage filename support.

    Args:
        filename (str | Path): 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)
    N)z.tiffz.tifé   r   é   é   )Úaxis).N)ÚstrÚnpÚfromfileÚuint8ÚFileNotFoundErrorÚOSErrorÚsizeÚcv2ÚIMREAD_GRAYSCALEÚlowerÚendswithÚimdecodemultiÚIMREAD_UNCHANGEDÚlenÚndimÚstackÚimdecodeÚPIL_FALLBACK_SUFFIXESÚ_imread_pil)r	   r   Ú
file_bytesÚsuccessÚframesÚims         úi/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/utils/patches.pyÚimreadr,      s[  € õ �8‰}Œ}€HðÝ”[ ­2¬8Ñ4Ô4ˆ
ˆ
øÝ�wÐ'ð ð ð ØˆtˆtðøøøàŒ?ð ØˆtØ•Ô$Ò$Ð$¨¯ªÑ)9Ô)9×)BÒ)BÐCTÑ)UÔ)UÐ$ÝÔ+¨J½Ô8LÑMÔM‰ˆ�Øð 	Ø�4Ýˆv‰;Œ;˜Š?ˆ?˜f Qœiœn°Ò1Ð1Ý # F¡¤¨qÒ 0Ð 0�6˜!”9�9µb´h¸vÈAÐ6NÑ6NÔ6NÐNÝ	Œ�j %Ñ	(Ô	(€Bà	€z�h—n’nÑ&Ô&×/Ò/Õ0EÑFÔF€zÝ˜ 5Ñ)Ô)ˆØ˜N¨r¬w¸!ª|¨|ˆ2ˆiŒ=ˆ=ÀÐCs   ‘1 ±AÁAFc                óØ   — t           rt          | g|¢R i |¤ŽS 	 t          | g|¢R i |¤ŽS # t          $ r6 ddlm}  |d¦  «         ddlm}  |¦   «          da t          | g|¢R 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_openr7   =   sÖ   € õ  ð 6Ý˜8Ð5 dÐ5Ð5Ð5¨fÐ5Ð5Ð5ð
6Ý˜8Ð5 dÐ5Ð5Ð5¨fÐ5Ð5Ð5øÝð 6ð 6ð 6Ø?Ð?Ð?Ð?Ð?Ð?àÐ˜9Ñ%Ô%Ð%Ø0Ð0Ð0Ð0Ð0Ð0àÐÑÔÐØ"&ÐÝ˜8Ð5 dÐ5Ð5Ð5¨fÐ5Ð5Ð5Ð5Ð5ð6øøøs   ™) ©=A)Á(A)r   c                ó�  — 	 t          j        | ¦  «        5 }|t          j        k    r3t	          j        |                     d¦  «        ¦  «        cddd¦  «         S t          j        t	          j        |                     d¦  «        ¦  «        t          j        ¦  «        cddd¦  «         S # 1 swxY w Y   dS # t          $ r Y dS 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   r   r   ÚasarrayÚconvertÚcvtColorÚCOLOR_RGB2BGRr2   )r	   r   Úimgs      r+   r&   r&   _   s0  € ðÝŒZ˜Ñ!Ô!ð 	S SØ�Ô,Ò,Ð,Ý”z #§+¢+¨cÑ"2Ô"2Ñ3Ô3ð	Sð 	Sð 	Sð 	Sñ 	Sô 	Sð 	Sð 	Sõ ”<¥¤
¨3¯;ª;°uÑ+=Ô+=Ñ >Ô >ÅÔ@QÑRÔRð	Sð 	Sð 	Sð 	Sñ 	Sô 	Sð 	Sð 	Sð 	Sð 	Sð 	Sð 	Søøøð 	Sð 	Sð 	Sð 	Sð 	Sð 	Søõ ð ð ð ØˆtˆtðøøøsA   ‚B7 –7B*ÁB7 ÁAB*ÂB7 Â*B.Â.B7 Â1B.Â2B7 Â7
CÃCc                ó°   — 	 t          j        | t           j        ¦  «        }n# t          t          f$ r Y dS w xY w|j        sdS t          j        ||¦  «        S )aç  Read an image with multilanguage filename support, preserving native cv2.imread behavior.

    This is intended as a Windows monkey-patch for cv2.imread. Unlike `imread`, it does not expand grayscale dimensions
    or handle TIFF/AVIF/HEIC fallback.

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

    Returns:
        (np.ndarray | None): The read image array, or None if reading fails.
    N)r   r   r   r   r   r   r   r$   )r	   r   r'   s      r+   Úimread_unicoderB   r   sd   € ðÝ”[ ­2¬8Ñ4Ô4ˆ
ˆ
øÝ�wÐ'ð ð ð ØˆtˆtðøøøàŒ?ð ØˆtÝŒ<˜
 EÑ*Ô*Ð*s   ‚" ¢7¶7r@   ú
np.ndarrayÚparamsúlist[int] | NoneÚboolc                ó¬   — 	 t          j        t          | ¦  «        j        ||¦  «        d                              | ¦  «         dS # t
          $ r Y dS 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Útofiler2   )r	   r@   rD   s      r+   ÚimwriterK   ˆ   s^   € ð$ÝŒ•T˜(‘^”^Ô*¨C°Ñ8Ô8¸Ô;×BÒBÀ8ÑLÔLÐLØˆtøÝð ð ð Øˆuˆuðøøøs   ‚AA Á
AÁAÚwinnameÚmatÚNonec                óp   — t          |                      d¦  «                             ¦   «         |¦  «         dS )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)rL   rM   s     r+   ÚimshowrT   ¡   s3   € õ" ˆG�NŠNÐ+Ñ,Ô,×3Ò3Ñ5Ô5°sÑ;Ô;Ð;Ð;Ð;ó    c                 óF   — 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_utilsrW   ÚtorchÚload)r5   r6   rW   s      r+   Ú
torch_loadr\   ¹   sG   € ð  9Ð8Ð8Ð8Ð8Ð8àð '�n¨FÐ2Ð2Ø!&ˆˆ~ÑåŒ:�tÐ&˜vÐ&Ð&Ð&rU   c                 ó¨   — t          d¦  «        D ]A}	 t          | i |¤Žc S # t          $ r$ |dk    r‚ t          j        d|z  dz  ¦  «         Y Œ>w xY wdS )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)r5   r6   Úis      r+   Ú
torch_savere   Ñ   s†   € õ �1‰XŒXð #ð #ˆð	#Ý Ð/¨Ð/Ð/Ð/Ð/Ð/øÝð 	#ð 	#ð 	#Ø�AŠvˆvØÝŒJ˜˜1™ ‘zÑ"Ô"Ð"Ð"Ð"ð	#øøøð#ð #s   “!¡+AÁAÚ ÚdynamicÚquantizeúint | str | NoneÚfmtc              #  ó¸   ‡K  — | rP|dk    rJ|dk    rDt           j        Šddœˆfd„
}|t           _        	 dV — ‰t           _        dS # ‰t           _        w xY wdV — dS )zwWorkaround for ONNX torch.arange incompatibility with FP16.

    https://github.com/pytorch/pytorch/issues/148041.
    é   ÚonnxN)Údtypec                ó:   •—  ‰|i |¤Ž                      | ¦  «        S )zNWrap torch.arange to cast dtype after creation instead of passing it directly.)Úto)rn   r5   r6   Úfuncs      €r+   Úarangezarange_patch.<locals>.arangeñ   s&   ø€ à�4˜Ð( Ð(Ð(×+Ò+¨EÑ2Ô2Ð2rU   )rZ   rr   )rg   rh   rj   rr   rq   s       @r+   Úarange_patchrs   è   s�   øè è € ð ð �8˜r’>�> c¨V¢m mÝŒ|ˆà $ð 	3ð 	3ð 	3ð 	3ð 	3ð 	3ð 	3ð �Œð	 ØˆEˆEˆEà�EŒLˆLˆLø˜4�EŒLÐÐÐÐàˆˆˆˆˆs   ³A ÁAc               #  óÎ   ‡K  — ddl m}  | rUt          j        j        Šˆfd„}|t          j        _        	 dV — ‰t          j        _        dS # ‰t          j        _        w xY wdV — dS )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© )r5   r6   rq   s     €r+   Útorch_exportz'onnx_export_patch.<locals>.torch_export  s#   ø€ à�4˜Ð6 Ð6Ð6°Ð6Ð6Ð6Ð6rU   N)rY   ru   rZ   rm   Úexport)ru   ry   rq   s     @r+   Úonnx_export_patchr{   þ   s“   øè è € ð 8Ð7Ð7Ð7Ð7Ð7àð ÝŒzÔ ˆð	7ð 	7ð 	7ð 	7ð 	7ð )�Œ
Ôð	%ØˆEˆEˆEà $�EŒJÔÐÐø �EŒJÔÐ$Ð$Ð$Ð$àˆˆˆˆˆs   ´A ÁAÚ	overridesúdict[str, Any] | Nonec              #  ó  K  — |r„t          | ¦  «        }|                     ¦   «         D ]\  }}t          | ||¦  «         Œ	 | V — | j                             |j        ¦  «         dS # | j                             |j        ¦  «         w xY w| V — dS )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)r5   r|   Úoriginal_argsÚkeyÚvalues        r+   Úoverride_configsr†     s¦   è è € ð ð 	Ý˜T™
œ
ˆØ#Ÿ/š/Ñ+Ô+ð 	&ð 	&‰JˆC�Ý�D˜#˜uÑ%Ô%Ð%Ð%ð	9ØˆJˆJˆJàŒM× Ò  Ô!7Ñ8Ô8Ð8Ð8Ð8øˆDŒM× Ò  Ô!7Ñ8Ô8Ð8Ð8øøøàˆ
ˆ
ˆ
ˆ
ˆ
s   Á A% Á%!B)r	   r
   r   r   r   r   )r	   r   r   r   r   r   )N)r	   r   r@   rC   rD   rE   r   rF   )rL   r   rM   rC   r   rN   )FNrf   )rg   rF   rh   ri   rj   r   )r|   r}   )$Ú__doc__Ú
__future__r   rb   Ú
contextlibr   r   Úpathlibr   Útypingr   r   Únumpyr   rZ   ÚPILr   rT   rQ   r%   ÚIMREAD_COLORr,   r;   r1   r0   r7   r&   rB   rK   Úsaver`   r\   re   rs   r{   r†   rx   rU   r+   ú<module>r�      s   ðà JÐ Jà "Ð "Ð "Ð "Ð "Ð "à €€€Ø %Ð %Ð %Ð %Ð %Ð %Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à 
€
€
€
Ø Ð Ð Ð Ø €€€Ø Ð Ð Ð Ð Ð ð Œ*€Ø3Ð ð /2Ô.>ð Dð Dð Dð Dð DðF Œj€ØÐ ð6ð 6ð 6ð> €„
ð -0Ô,<ð ð ð ð ð ð& 7:Ô6Fð +ð +ð +ð +ð +ð,ð ð ð ð ð2<ð <ð <ð <ð* Œj€ð'ð 'ð 'ð0#ð #ð #ð. ðð ð ð ñ „ðð* ðð ñ „ðð( ðð ð ð ñ „ðð ð rU   