o
    Ďi	                     @  s~   d dl mZ d dlZd dlmZ d dlmZmZ d dlZ	d dl
mZ er(d dlZddd	ZdddZdddZddddZdS )    )annotationsN)environ)TYPE_CHECKINGAny)ImagereturnNonec                  C  s   dd l } | j  d S )Nr   )torchcudaempty_cache)r	    r   R/home/jeff/fluffinator/venv/lib/python3.10/site-packages/sahi/utils/torch_utils.pyempty_cuda_cache   s   r   imgnp.ndarray | Imagetorch.Tensorc                 C  sZ   ddl }t| tjr| }nt| }|d}|t| }| dkr+|d }|S )zConverts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C
    x H x W).

    Args:
        img: PIL.Image or numpy array
    Returns:
        torch.tensor
    r   N)   r      r      )	r	   
isinstancenpndarrayarray	transpose
from_numpyfloatmax)r   r	   nparraytensorr   r   r   to_float_tensor   s   	

r   r   
np.ndarrayc                 C  s&   |   } |  dkr| d } | dS )Nr   r   )r   r   r   )numpyr   r   )r   r   r   r   torch_to_numpy+   s   
r"   device
str | Nonetorch.devicec                 C  s   ddl }| dks| du rd} t|   dddd} | dk}| d	k}|s*|r/d
td< n| r5| td< d}tt|| }|sT|sT|j	
 rT|rT| rQd|  nd}n|ret|ddre|jj
 red	}nd}||S )a|  Selects torch device.

    Args:
        device: "cpu", "mps", "cuda", "cuda:0", "cuda:1", etc.
                When no device string is given, the order of preference
                to try is: cuda:0 > mps > cpu

    Returns:
        torch.device

    Inspired by https://github.com/ultralytics/yolov5/blob/6371de8879e7ad7ec5283e8b95cc6dd85d6a5e72/utils/torch_utils.py#L107
    r   Nr
   zcuda:0zcuda: nonecpumpsz-1CUDA_VISIBLE_DEVICESz^(0|[1-9]\d*)$has_mpsF)r	   strstriplowerreplacer   boolre	fullmatchr
   is_availablegetattrbackendsr)   r#   )r#   r	   r(   r)   cuda_id_patternvalid_cuda_idargr   r   r   select_device2   s$    

r9   )r   r   )r   r   r   r   )r   r   r   r    )N)r#   r$   r   r%   )
__future__r   r1   osr   typingr   r   r!   r   	PIL.Imager   r	   r   r   r"   r9   r   r   r   r   <module>   s    


