
    h                       S r SSKJr  SSKrSSKJr  SSKJr  SSKJr  SSK	J
r
  SSKrSSKrSSKr\R                  r\R"                  4SS jjrSSS	 jjrSS
 jr\R(                  rS rS r\S 5       r\SSS jj5       rg)zDMonkey patches to update/extend functionality of existing functions.    )annotationsN)contextmanager)copy)Path)Anyc                   [         R                  " U [         R                  5      nU R                  S5      (       ak  [        R
                  " U[        R                  5      u  p4U(       a<  [        U5      S:X  a  US   R                  S:X  a  US   $ [         R                  " USS9$ g[        R                  " X!5      nUb  UR                  S:X  a  US   $ U$ )	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)filenameflags
file_bytessuccessframesims         S/home/james-whalen/.local/lib/python3.13/site-packages/ultralytics/utils/patches.pyimreadr      s     Xrxx0J*++++J8L8LM #Fq 0VAY^^q5H6!9fbhhW]deNff\\*, "277a<r)}GRG    c                     [         R                  " [        U 5      R                  X5      S   R	                  U 5        g! [
         a     gf = f)a  
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   imgparamss      r   imwriter(   /   sD    &T(^**C8;BB8L s   <? 
AAc                V    [        U R                  S5      R                  5       U5        g)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)winnamemats     r   imshowr0   I   s!    $ GNN+,335s;r    c                 ^    SSK Jn  U(       a  SU;  a  SUS'   [        R                  " U 0 UD6$ )a  
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_utilsr2   torchload)argskwargsr2   s      r   
torch_loadr9   b   s/    " 9nF2!&~::t&v&&r    c                     [        S5       H  n [        U 0 UD6s  $    g! [         a/  nUS:X  a  Ue[        R                  " SU-  S-  5         SnAMH  SnAff = f)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)r7   r8   ies       r   
torch_saverC   {   s\     1X	#///   	#AvJJ1z""	#s   
 
A$AAc              #     ^#    U R                   (       aV  U R                  (       aE  U R                  S:X  a5  [        R                  mSS.U4S jjnU[        l        Sv   T[        l        gSv   g7f)zp
Workaround for ONNX torch.arange incompatibility with FP16.

https://github.com/pytorch/pytorch/issues/148041.
onnxN)dtypec                2   > T" U0 UD6R                  U 5      $ )zPReturn a 1-D tensor of size with values from the interval and common difference.)to)rF   r7   r8   funcs      r   arangearange_patch.<locals>.arange   s    ((++E22r    )dynamichalfformatr5   rJ   )r7   rJ   rI   s     @r   arange_patchrO      sL      ||		dkkV&;|| $ 	3 	3 s   A-A0c              #  ,  #    U(       a[  [        U 5      nUR                  5        H  u  p4[        XU5        M      U v   U R                  R	                  UR                  5        gU v   g! U R                  R	                  UR                  5        f = f7f)a(  
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)r7   	overridesoriginal_argskeyvalues        r   override_configsrY      sr      T
#//+JCDu% ,	9JMM  !7!78
 MM  !7!78s   8BA* +B*'BB)r   strr   intreturnznp.ndarray | None)N)r   rZ   r&   
np.ndarrayr'   zlist[int] | Noner\   bool)r.   rZ   r/   r]   r\   None)rU   zdict[str, Any] | None)__doc__
__future__r   r?   
contextlibr   r   pathlibr   typingr   r   numpyr   r5   r0   r+   IMREAD_COLORr   r(   saver=   r9   rC   rO   rY    r    r   <module>ri      s    J "  %    
   ** (+'7'7 H64<, jj'2#0  (  r    