
    j0%                    H   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j        Zd Zd Zed,d-d#            Zed$             Z ed)d.d'            Z!dS )/zDMonkey patches to update/extend functionality of existing functions.    )annotationsN)contextmanager)copy)Path)Any)Imagefilenamestrflagsintreturnnp.ndarray | Nonec                8   	 t          j        | t           j                  }n# t          t          f$ r Y dS w xY w|                     d          rht          j        |t          j                  \  }}|rBt          |          dk    r|d         j
        dk    r|d         nt          j        |d          S dS t          j        ||          }|7|                                                     d          rt          | |          }||j
        dk    r|d	         n|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)
    N)z.tiffz.tif   r         )axis)z.avifz.heic).N)npfromfileuint8FileNotFoundErrorOSErrorendswithcv2imdecodemultiIMREAD_UNCHANGEDlenndimstackimdecodelower_imread_pil)r	   r   
file_bytessuccessframesims         \/var/www/html/Carbon-Document/venv/lib/python3.11/site-packages/ultralytics/utils/patches.pyimreadr(      s   [2844

w'   tt*++ H+J8LMM 	g #Fq 0 0VAY^q5H5H6!99bhW]deNfNfNfft\*e,,:(..**334FGG:Xu--B "27a<<r)}}RGs   " 77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_openr3   :   s       685d555f555
685d555f555 6 6 6??????9%%%000000"&85d555f555556s   ) =A)(A)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   IMREAD_GRAYSCALEr   asarrayconvertcvtColorCOLOR_RGB2BGRr.   )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    ttsA   B7 7B*B7 AB*B7 *B..B7 1B.2B7 7
CC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tofiler.   )r	   r=   r?   s      r'   imwriterF   o   s^    $T(^^*C88;BB8LLLt   uu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)rG   rH   s     r'   imshowrO      s3    " GNN+,,3355s;;;;;    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_utilsrR   torchload)r1   r2   rR   s      r'   
torch_loadrW      sG      988888 'nF22!&~:t&v&&&rP   c                     t          d          D ]I}	 t          | i |c S # t          $ r,}|dk    r|t          j        d|z  dz             Y d}~Bd}~w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)r1   r2   ies       r'   
torch_savera      s     1XX # #	#////// 	# 	# 	#AvvJ1z""""""""	## #s   !
A"AA dynamichalffmtc              #     K   | r:|r8|dk    r2t           j        ddfd
}|t           _        dV  t           _        dS 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)rh   r1   r2   funcs      r'   arangezarange_patch.<locals>.arange   s&    4(((++E222rP   )rU   rl   )rc   rd   re   rl   rk   s       @r'   arange_patchrm      sw        4 C6MM| $ 	3 	3 	3 	3 	3 	3 	3 rP   c               #     K   ddl m}  | r>t          j        j        fd}|t          j        _        dV  t          j        _        dS 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 )r1   r2   rk   s     r'   torch_exportz'onnx_export_patch.<locals>.torch_export   s#    46666666rP   N)rT   ro   rU   rg   export)ro   rs   rk   s     @r'   onnx_export_patchru      sx       877777 z 	7 	7 	7 	7 	7 )
 
rP   	overridesdict[str, Any] | Nonec              #    K   |rt          |           }|                                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)r1   rv   original_argskeyvalues        r'   override_configsr      s        	T

#//++ 	& 	&JCD#u%%%%	9JJJM  !788888DM  !78888




s    A% %!B)r	   r
   r   r   r   r   )N)r	   r
   r=   r>   r?   r@   r   rA   )rG   r
   rH   r>   r   rI   )FFrb   )rc   rA   rd   rA   re   r
   )rv   rw   )"__doc__
__future__r   r]   
contextlibr   r   pathlibr   typingr   r   numpyr   rU   PILr   rO   rL   IMREAD_COLORr(   r7   r-   r,   r3   r"   rF   saver[   rW   ra   rm   ru   r   rr   rP   r'   <module>r      s   J J " " " " " "  % % % % % %                   



            * (+'7 H H H H HB j 6 6 6> 
 -0,<     &    2< < < <* j' ' '0# # #.     &   $       rP   