o
    Ďi#                      @  s  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZ	d dl
Z
d dlmZ d dlZd;ddZd<d=ddZG dd dejZd>d?ddZdgdfd@ddZdgdfdAd"d#ZdBd%d&ZdBd'd(Zd)d* Zd+d, Zd-d. ZdCdDd3d4ZdEd7d8Zd9d: ZdS )F    )annotationsN)Path	file_pathstrdest_dirc                 C  s:   t | }|| W d   dS 1 sw   Y  dS )zxUnzips compressed .zip file.

    Example inputs:
        file_path: 'data/01_alb_id.zip'
        dest_dir: 'data/'
    N)zipfileZipFile
extractall)r   r   zf r   K/home/jeff/fluffinator/venv/lib/python3.10/site-packages/sahi/utils/file.pyunzip   s   	"r   indent
int | Nonec                 C  s\   t |jjddd t|ddd}tj| |dt|d W d   dS 1 s'w   Y  dS )	z
    Saves json formatted data (given as "data") as save_path
    Example inputs:
        data: {"image_id": 5}
        save_path: "dirname/coco.json"
        indent: Train json files with indent=None, val json files with indent=4
    Tparentsexist_okwutf-8encoding),:)
separatorsclsr   N)r   parentmkdiropenjsondumpNumpyEncoder)data	save_pathr   outfiler   r   r   	save_json   s   	"r$   c                      s   e Zd Z fddZ  ZS )r    c                   sH   t |tjr
t|S t |tjrt|S t |tjr| S t 	|S N)

isinstancenpintegerintfloatingfloatndarraytolistsuperdefault)selfobj	__class__r   r   r/   /   s   zNumpyEncoder.default)__name__
__module____qualname__r/   __classcell__r   r   r2   r   r    .   s    r    r   	load_pathr   c                 C  s<   t | |d}t|}W d   |S 1 sw   Y  |S )zLoads json formatted data (given as "data") from load_path Encoding type can be specified with 'encoding'
    argument.

    Example inputs:
        load_path: "dirname/coco.json"
    r   N)r   r   load)r8   r   	json_filer!   r   r   r   	load_json:   s   
r;   z.json   	directorycontainslistverboser)   return	list[str]c                   s   |rt ndd }g }t| D ] t fdd|D r*ttj|  }|| qt|}t	| j
}|d|d| d |S )a  Walk given directory and return a list of file path with desired extension.

    Args:
        directory: str
            "data/coco/"
        contains: list
            A list of strings to check if the target file contains them, example: ["coco.png", ".jpg", "jpeg"]
        verbose: int
            0: no print
            1: print number of files

    Returns:
        filepath_list : list
            List of file paths
    c                  _     d S r%   r   akr   r   r   <lambda>\       zlist_files.<locals>.<lambda>c                 3      | ]	}|   v V  qd S r%   lower.0
strtocheckfiler   r   	<genexpr>b       zlist_files.<locals>.<genexpr>
There are z listed files in folder: /)printoslistdiranyr   pathjoinappendlenr   name)r=   r>   r@   verboseprintfilepath_listfilepathnumber_of_filesfolder_namer   rO   r   
list_filesG   s   

rc   Tbooltuple[list, list]c                   s   |rt ndd }g }g }t| D ]-\}}}|D ]% t fdd|D r=tj| }	||	 |	| d }
||
 qqt|}| tj	d }|d| d| d ||fS )	a1  Walk given directory recursively and return a list of file path with desired extension.

    Arguments
    -------
        directory : str
            "data/coco/"
        contains : list
            A list of strings to check if the target file contains them, example: ["coco.png", ".jpg", "jpeg"]
        verbose : bool
            If true, prints some results
    Returns
    -------
        relative_filepath_list : list
            List of file paths relative to given directory
        abs_filepath_list : list
            List of absolute file paths
    c                  _  rC   r%   r   rD   r   r   r   rG      rH   z(list_files_recursively.<locals>.<lambda>c                 3  rI   r%   rJ   rL   rO   r   r   rQ      rR   z)list_files_recursively.<locals>.<genexpr>rS   z listed files in folder .)
rU   rV   walkrX   rY   rZ   r[   splitr\   sep)r=   r>   r@   r^   abs_filepath_listrelative_filepath_listr_fabs_filepathrelative_filepathra   rb   r   rO   r   list_files_recursivelyn   s    

rr   rY   c                 C  s"   t | }tj|\}}||fS )zZTakes a file path, returns (base_filename_with_extension, base_filename_without_extension))ntpathbasenamerV   rY   splitext)rY   base_filename_with_extensionbase_filename_without_extensionrn   r   r   r   get_base_filename   s   
rx   c                 C  s   t j| \}}|S )zGet the file extension from a given file path.

    Args:
        path (str): The file path.

    Returns:
        str: The file extension.
    )rV   rY   ru   )rY   rn   file_extensionr   r   r   get_file_extension   s   	rz   c                 C  s:   t | d}t|}W d   |S 1 sw   Y  |S )z
    Loads pickle formatted data (given as "data") from load_path
    Example inputs:
        load_path: "dirname/coco.pickle"
    rbN)r   pickler9   )r8   r:   r!   r   r   r   load_pickle   s   
r}   c                 C  sP   t |jjddd t|d}t| | W d   dS 1 s!w   Y  dS )z
    Saves pickle formatted data (given as "data") as save_path
    Example inputs:
        data: {"image_id": 5}
        save_path: "dirname/coco.pickle"
    Tr   wbN)r   r   r   r   r|   r   )r!   r"   r#   r   r   r   save_pickle   s   "r   c                 C  s"   t d|  |gd}t||}|S )a4  Imports a predefined detection class by class name.

    Args:
        model_type: str
            "yolov5", "detectron2", "mmdet", "huggingface" etc
        model_name: str
            Name of the detection model class (example: "MmdetDetectionModel")
    Returns:
        class_: class with given path
    zsahi.models.)fromlist)
__import__getattr)
model_type
class_namemoduleclass_r   r   r   import_model_class   s   
r    
str | Pathr   rj   c                   s~   t     r
|s  st S t   d} fdd|D }dd |D }|r5t|d nd}   | S )a2  Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc.

    Args:
        path: str
            The base path to increment.
        exist_ok: bool
            If True, return the path as is if it already exists. If False, increment the path.
        sep: str
            The separator to use between the base path and the increment number.

    Returns:
        str: The incremented path.

    Example:
        >>> increment_path("runs/exp", sep="_")
        'runs/exp_0'
        >>> increment_path("runs/exp_0", sep="_")
        'runs/exp_1'
    *c                   s&   g | ]}t d  d j |qS )z%sz(\d+))researchstem)rM   drY   rj   r   r   
<listcomp>   s   & z"increment_path.<locals>.<listcomp>c                 S  s    g | ]}|rt | d  qS )r   )r)   groups)rM   mr   r   r   r      s     r<      )r   existsr   globmax)rY   r   rj   dirsmatchesindicesnr   r   r   increment_path   s   r   from_urlto_pathc                 C  s6   t |jjddd tj|stj| | dS dS )zDownloads a file from the given URL and saves it to the specified path.

    Args:
        from_url (str): The URL of the file to download.
        to_path (str): The path where the downloaded file should be saved.

    Returns:
        None
    Tr   N)	r   r   r   rV   rY   r   urllibrequesturlretrieve)r   r   r   r   r   download_from_url   s   
r   c                  C  s   ddl } d| jv S )zCheck if the current environment is a Google Colab instance.

    Returns:
        bool: True if the environment is a Google Colab instance, False otherwise.
    r   Nzgoogle.colab)sysmodules)r   r   r   r   is_colab
  s   
r   )r   r   r   r   r%   )r   r   )r   )r8   r   r   r   )r=   r   r>   r?   r@   r)   rA   rB   )r=   r   r>   r?   r@   rd   rA   re   )rY   r   )Tr   )rY   r   r   rd   rj   r   rA   r   )r   r   r   r   )
__future__r   r   r   rs   rV   r|   r   urllib.requestr   r   pathlibr   numpyr'   r   r$   JSONEncoderr    r;   rc   rr   rx   rz   r}   r   r   r   r   r   r   r   r   r   <module>   s6    
'
,

