
    |hu              	          d 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	m
Z
mZ ddlZddlZddlZej                   Zej$                  fdeded	eej*                     fd
Zddedej*                  dee
e      d	efdZdedej*                  d	dfdZej2                  Zd Zd Zed        Zeddee	eef      fd       Zy)zDMonkey patches to update/extend functionality of existing functions.    N)contextmanager)copy)Path)AnyDictListOptionalfilenameflagsreturnc                    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                  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).N)npfromfileuint8endswithcv2imdecodemultiIMREAD_UNCHANGEDlenndimstackimdecode)r
   r   
file_bytessuccessframesims         X/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/utils/patches.pyimreadr"      s     Xrxx0J*+++J8L8LM #Fq 0VAY^^q5H6!9fbhhW]deNff\\*e, "1r)}4"4    imgparamsc                     	 t        j                  t        |       j                  ||      d   j	                  |        y# t
        $ r Y yw xY w)aI  
    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tofile	Exception)r
   r$   r%   s      r!   imwriter+   -   sF    &T(^**C8;BB8L s   <? 	A
Awinnamematc                 V    t        | j                  d      j                         |       y)a=  
    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)r,   r-   s     r!   imshowr3   G   s!    $ GNN+,335s;r#   c                  N    ddl m} |r	d|vrd|d<   t        j                  | i |S )aH  
    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 2.0 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_utilsr5   torchload)argskwargsr5   s      r!   
torch_loadr<   `   s/    " 9nF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_saverF   y   sa     1X #	#///#  	#AvJJ1z""	#s   
	A"AAc              #      K   | j                   rN| j                  rB| j                  dk(  r3t        j                  ddfd
}|t        _        d t        _        yd yw)z|
    Workaround for ONNX torch.arange incompatibility with FP16.

    https://github.com/pytorch/pytorch/issues/148041.
    onnxN)dtypec                 2     |i |j                  |       S )zPReturn a 1-D tensor of size with values from the interval and common difference.)to)rI   r:   r;   funcs      r!   arangezarange_patch.<locals>.arange   s    ((++E22r#   )dynamichalfformatr8   rM   )r:   rM   rL   s     @r!   arange_patchrQ      sH      ||		dkkV&;|| $ 	3 s   A A#	overridesc              #   "  K   |r[t        |       }|j                         D ]  \  }}t        | ||        	 |  | j                  j	                  |j                         y|  y# | j                  j	                  |j                         w xY ww)aD  
    Context manager to temporarily override configurations in args.

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

    Yields:
        (IterableSimpleNamespace): Configuration arguments with overrides applied.
    N)r   itemssetattr__dict__update)r:   rR   original_argskeyvalues        r!   override_configsr[      s|      T
#//+ 	&JCD#u%	&	9JMM  !7!78
 MM  !7!78s   3BA% +B%'BB)N)__doc__rB   
contextlibr   r   pathlibr   typingr   r   r   r	   r   numpyr   r8   r3   r0   IMREAD_COLORstrintndarrayr"   boolr+   saver@   r<   rF   rQ   r[    r#   r!   <module>rh      s    J  %   , , 
   ** (+'7'7 5S 5 5HRZZ<P 56c 

 HT#Y4G SW 4<C <bjj <T <, jj'2#0  ( htCH~&>  r#   