a
    yfU                  	   @   s  d dl Z d dlZd dl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 d dlZd dlZd dlmZmZmZmZmZmZmZ dZdd	 d
D dd	 d
D  dd	 d
D  dd	 dD  dd	 dD  dd	 dD  dd	 dD  dd	 dD  dd	 dD  dd	 dD  dd	 dD  dd	 dD  dg dg Zd d	 eD Zd?d"d#Zd@d%d&ZdAd(d)ZdBd*d+Zd,e	 d-d'fd.d/Zd0d1 Z dCd4d5Z!dDd7d8Z"dEd:d;Z#e	 d'd!d!d<d2d!fd=d>Z$dS )F    N)repeat)
ThreadPool)Path)parserequest)LOGGERTQDMchecks	clean_urlemojis	is_onlineurl2fileultralytics/assetsc                 C   s&   g | ]}d D ]}d| | dqqS )) -cls-seg-pose-obbz-oiv7yolov8.pt .0ksuffixr   r   W/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/utils/downloads.py
<listcomp>       r   Znsmlxc                 C   s&   g | ]}d D ]}d| | dqqS ))r   r   r   r   r   Zyolo11r   r   r   r   r   r   r      r   c                 C   s&   g | ]}d D ]}d| | dqqS ))r   6Zyolov5u.ptr   )r   r   
resolutionr   r   r   r      r   c                 C   s   g | ]}d | dqS )Zyolov3r   r   r   r   r   r   r   r      r   )r   z-sppz-tinyc                 C   s   g | ]}d | dqS )r   z	-world.ptr   r!   r   r   r   r      r   Zsmlxc                 C   s   g | ]}d | dqS )r   z-worldv2.ptr   r!   r   r   r   r      r   c                 C   s   g | ]}d | dqS )Zyolov9r   r   r!   r   r   r   r      r   Ztsmcec                 C   s   g | ]}d | dqS )Zyolov10r   r   r!   r   r   r   r      r   Znsmblxc                 C   s   g | ]}d | dqS )Z	yolo_nas_r   r   r!   r   r   r   r      r   smlc                 C   s   g | ]}d | dqS )Zsam_r   r   r!   r   r   r   r      r   blc                 C   s   g | ]}d | dqS )zFastSAM-r   r   r!   r   r   r   r      r   sxc                 C   s   g | ]}d | dqS )zrtdetr-r   r   r!   r   r   r   r      r   lxzmobile_sam.ptz:calibration_image_sample_data_20x128x128x3_float32.npy.zipc                 C   s   g | ]}t |jqS r   )r   stemr!   r   r   r   r   #   r   Fc              	   C   s   t t t| } t| }t|j|jgs2J |rzt	
| *}| dkW  d   W  d   S 1 sp0    Y  W d   dS 1 s0    Y  dS )a(  
    Validates if the given string is a URL and optionally checks if the URL exists online.

    Args:
        url (str): The string to be validated as a URL.
        check (bool, optional): If True, performs an additional check to see if the URL exists online.
            Defaults to False.

    Returns:
        (bool): Returns True for a valid URL. If 'check' is True, also returns True if the URL exists online.
            Returns False otherwise.

    Example:
        ```python
        valid = is_url("https://www.example.com")
        ```
       NTF)
contextlibsuppress	Exceptionstrr   urlparseallschemenetlocr   urlopengetcode)urlcheckresultresponser   r   r   is_url&   s    
8 r6   z	.DS_StoreZ__MACOSXc                 C   sH   |D ]>}t t| |}td| d|  |D ]}|  q4qdS )ao  
    Deletes all ".DS_store" files under a specified directory.

    Args:
        path (str, optional): The directory path where the ".DS_store" files should be deleted.
        files_to_delete (tuple): The files to be deleted.

    Example:
        ```python
        from ultralytics.utils.downloads import delete_dsstore

        delete_dsstore("path/to/dir")
        ```

    Note:
        ".DS_store" files are created by the Apple operating system and contain metadata about folders and files. They
        are hidden system files and can cause issues when transferring files between different operating systems.
    z	Deleting z files: N)listr   rglobr   infounlink)pathZfiles_to_deletefilematchesfr   r   r   delete_dsstoreC   s
    r@   Tc                    s   ddl m}m}m} t|  t| } |  s<td|  d fdd| dD }| 	d}|rf|n|}	||d	|	H}
t
|d
|  d| dd| dD ]}|
|||  qW d   n1 s0    Y  |S )a  
    Zips the contents of a directory, excluding files containing strings in the exclude list. The resulting zip file is
    named after the directory and placed alongside it.

    Args:
        directory (str | Path): The path to the directory to be zipped.
        compress (bool): Whether to compress the files while zipping. Default is True.
        exclude (tuple, optional): A tuple of filename strings to be excluded. Defaults to ('.DS_Store', '__MACOSX').
        progress (bool, optional): Whether to display a progress bar. Defaults to True.

    Returns:
        (Path): The path to the resulting zip file.

    Example:
        ```python
        from ultralytics.utils.downloads import zip_directory

        file = zip_directory("path/to/dir")
        ```
    r   )ZIP_DEFLATED
ZIP_STOREDZipFilezDirectory 'z' does not exist.c                    s.   g | ]&    rt fd dD r qS )c                 3   s   | ]}| j vV  qd S Nnamer   xr?   r   r   	<genexpr>z   r   z+zip_directory.<locals>.<listcomp>.<genexpr>)is_filer-   r   excluderI   r   r   z   r   z!zip_directory.<locals>.<listcomp>*.zipwzZipping  to ...r=   descunitdisableN)zipfilerA   rB   rC   r@   r   is_dirFileNotFoundErrorr9   with_suffixr   writerelative_to)	directorycompressrN   progressrA   rB   rC   Zfiles_to_zipzip_filecompressionr?   r=   r   rM   r   zip_directory]   s    
$2rc   c                    s  ddl m}m}m} t|  r(|| s8|d|  d|du rJt| j}|| } fdd| D }	dd	 |	D }
t|
d
k}|r|}t|t	|
d  }nt|t| j
  }}| rt| r|std|  d| d |W  d   S t|	d|  dt|  dd| dD ]8}dt|jv rNtd| d q$||| q$W d   n1 st0    Y  |S )a  
    Unzips a *.zip file to the specified path, excluding files containing strings in the exclude list.

    If the zipfile does not contain a single top-level directory, the function will create a new
    directory with the same name as the zipfile (without the extension) to extract its contents.
    If a path is not provided, the function will use the parent directory of the zipfile as the default path.

    Args:
        file (str): The path to the zipfile to be extracted.
        path (str, optional): The path to extract the zipfile to. Defaults to None.
        exclude (tuple, optional): A tuple of filename strings to be excluded. Defaults to ('.DS_Store', '__MACOSX').
        exist_ok (bool, optional): Whether to overwrite existing contents if they exist. Defaults to False.
        progress (bool, optional): Whether to display a progress bar. Defaults to True.

    Raises:
        BadZipFile: If the provided file does not exist or is not a valid zipfile.

    Returns:
        (Path): The path to the directory where the zipfile was extracted.

    Example:
        ```python
        from ultralytics.utils.downloads import unzip_file

        dir = unzip_file("path/to/file.zip")
        ```
    r   )
BadZipFilerC   
is_zipfilezFile 'z&' does not exist or is a bad zip file.Nc                    s&   g | ] t  fd dD r qS )c                 3   s   | ]}| vV  qd S rD   r   rG   rI   r   r   rJ      r   z(unzip_file.<locals>.<listcomp>.<genexpr>)r-   rL   rM   rI   r   r      r   zunzip_file.<locals>.<listcomp>c                 S   s   h | ]}t |jd  qS )r   )r   parts)r   r?   r   r   r   	<setcomp>   r   zunzip_file.<locals>.<setcomp>   u   WARNING ⚠️ Skipping z  unzip as destination directory z is not empty.
Unzipping rR   rS   r=   rT   z..z Potentially insecure file path: z, skipping extraction.)rX   rd   rC   re   r   existsparentnamelistlenr8   r&   anyiterdirr   warningr   resolverf   extract)r=   r<   rN   exist_okr`   rd   rC   re   ZzipObjfilesZtop_level_dirsZunzip_as_dirextract_pathr?   r   rM   r   
unzip_file   s,    
,0rv   z(https://ultralytics.com/assets/coco8.zipg      ?c           
         s   z6t | }|jdk s4J d|  d|j d|j W n tyJ   Y dS 0 d t|jdd  } fd	d
t	|D \}}}|| |k rdS d|dd|| dd|| | dd}	|rt
|	t|	 dS )aP  
    Check if there is sufficient disk space to download and store a file.

    Args:
        url (str, optional): The URL to the file. Defaults to 'https://ultralytics.com/assets/coco8.zip'.
        path (str | Path, optional): The path or drive to check the available free space on.
        sf (float, optional): Safety factor, the multiplier for the required free space. Defaults to 1.5.
        hard (bool, optional): Whether to throw an error or not on insufficient disk space. Defaults to True.

    Returns:
        (bool): True if there is sufficient disk space, False otherwise.
    i  zURL error for :  Ti   @Content-Lengthr   c                 3   s   | ]}|  V  qd S rD   r   rG   Zgibr   r   rJ      r   z#check_disk_space.<locals>.<genexpr>u,   WARNING ⚠️ Insufficient free disk space z.1fz GB < z.3fz GB required, Please free z( GB additional disk space and try again.F)requestsheadstatus_codereasonr*   intheadersgetshutil
disk_usageMemoryErrorr   rp   )
r2   r<   Zsfhardrdatatotalusedfreetextr   rz   r   check_disk_space   s$    
,
r   c           	      C   s   |  dd  dd }d| }d}t }|j|dd}d	t|j v rdttd
|  d|j	
 D ] \}}|drn|d| 7 }qn|jd}|rtd|d }W d   n1 s0    Y  ||fS )ax  
    Retrieves the direct download link and filename for a shareable Google Drive file link.

    Args:
        link (str): The shareable link of the Google Drive file.

    Returns:
        (str): Direct download URL for the Google Drive file.
        (str): Original filename of the Google Drive file. If filename extraction fails, returns None.

    Example:
        ```python
        from ultralytics.utils.downloads import get_google_drive_file_info

        link = "https://drive.google.com/file/d/1cqT-cJgANNrhIHCrEufUYhQ4RqiWG_lJ/view?usp=drive_link"
        url, filename = get_google_drive_file_info(link)
        ```
    z/d/rh   z/viewr   z/https://drive.google.com/uc?export=download&id=NT)streamzquota exceededui   ❌  Google Drive file download quota exceeded. Please try again later or download this file manually at .Zdownload_warningz	&confirm=zcontent-dispositionzfilename="(.+)")splitr{   Sessionr   r+   contentlowerConnectionErrorr   cookiesitems
startswithr   refindall)	linkZfile_idZ	drive_urlfilenamesessionr5   r   vcdr   r   r   get_google_drive_file_info   s(    


.r            ?c
                 C   s  |  d}
|
rt| \} }t|p"d|p.t|  }dt| vrVt|  rVt| }nv| s|
rh| nt| dd}d| d| d}t	| d	 |j
jd
d
d t| |j
d t|d D ]}zj|s|dkr(d|	  }tddd| d| d|ddddg
j}|dks
J d| nd}|dkrJtjj| ||	d nt| }tt|dd||	 dd
dd`}t|d4}|D ]}|| |t| qW d    n1 s0    Y  W d    n1 s0    Y  W d    n1 s 0    Y  | r4| j|kr,W  q|   W q t!y } zx|dkrrt" srt#t$d!| d"|n ||krt#t$d!| d#|t%d$|d  d%| d&| d	 W Y d }~qd }~0 0 q|r~| r~|j&d'v r~dd(l'm(} |p|j
) }||r t*||||	d)}nL|j&d*v rlt	d+| d,| d	 tjd-|j&d.krZd/nd0|d1|gd
d2 |rz|   |S d S )3a  
    Downloads files from a URL, with options for retrying, unzipping, and deleting the downloaded file.

    Args:
        url (str): The URL of the file to be downloaded.
        file (str, optional): The filename of the downloaded file.
            If not provided, the file will be saved with the same name as the URL.
        dir (str, optional): The directory to save the downloaded file.
            If not provided, the file will be saved in the current working directory.
        unzip (bool, optional): Whether to unzip the downloaded file. Default: True.
        delete (bool, optional): Whether to delete the downloaded file after unzipping. Default: False.
        curl (bool, optional): Whether to use curl command line tool for downloading. Default: False.
        retry (int, optional): The number of times to retry the download in case of failure. Default: 3.
        min_bytes (float, optional): The minimum number of bytes that the downloaded file should have, to be considered
            a successful download. Default: 1E0.
        exist_ok (bool, optional): Whether to overwrite existing contents during unzipping. Defaults to False.
        progress (bool, optional): Whether to display a progress bar during the download. Default: True.

    Example:
        ```python
        from ultralytics.utils.downloads import safe_download

        link = "https://ultralytics.com/assets/bus.jpg"
        path = safe_download(link)
        ```
    zhttps://drive.google.com/r   ://z?https://github.com/ultralytics/assets/releases/download/v0.0.0/zhttps://ultralytics.com/assets/zDownloading z to ''rS   Tparentsrs   )r<   rh   r   ZsScurlz-#-Lz-oz--retry3z-CzCurl return value torch)r`   ry   Bi   )r   rU   rW   rV   Z
unit_scaleZunit_divisorwbNu   ❌  Download failure for z. Environment is not online.z. Retry limit reached.u"   ⚠️ Download failure, retrying /rx   >   r   rP   .gz.tar)re   )r=   r<   rs   r`   >   r   r   ri   rR   tarr   ZxfZxfzz--directory)r3   )+r   r   r   r   r+   rK   r
   replacer   r:   rk   mkdirr   range
subprocessrun
returncoder   ZhubZdownload_url_to_filer   r0   r   r   	getheaderopenr\   updaterm   rj   statst_sizer;   r*   r   r   r   rp   r   rX   re   rq   rv   )r2   r=   dirunzipdeleter   retry	min_bytesrs   r`   Zgdriver?   urirU   isr   methodr5   ZpbarZf_openedr   ere   Z	unzip_dirr   r   r   safe_download  st    &


(

r

:
(r   latestc                 C   s   |dkrd| }d|  d| }t |}|jdkrN|jdkrN|rNt |}|jdkrtd| d|j d	|j  d
g fS | }|d dd |d D fS )a  
    Retrieve the specified version's tag and assets from a GitHub repository. If the version is not specified, the
    function fetches the latest release assets.

    Args:
        repo (str, optional): The GitHub repository in the format 'owner/repo'. Defaults to 'ultralytics/assets'.
        version (str, optional): The release version to fetch assets from. Defaults to 'latest'.
        retry (bool, optional): Flag to retry the request in case of a failure. Defaults to False.

    Returns:
        (tuple): A tuple containing the release tag and a list of asset names.

    Example:
        ```python
        tag, assets = get_github_assets(repo="ultralytics/assets", version="latest")
        ```
    r   ztags/zhttps://api.github.com/repos/z
/releases/r'   zrate limit exceededu'   ⚠️ GitHub assets check failure for rw   rx   r   Ztag_namec                 S   s   g | ]}|d  qS rE   r   rG   r   r   r   r     r   z%get_github_assets.<locals>.<listcomp>assets)r{   r   r}   r~   r   rp   json)repoversionr   r2   r   r   r   r   r   get_github_assets}  s    



 r   v8.3.0c           
      K   s  ddl m} t| } t| } t|  dd} |  rBt| S |d |   rbt|d |  S tt	
t| j}d| d}t| drt| d	d
}t|} t|  rtdt| d|   ntf || dd| n|tkr$|tv r$tf | d| d| | dd| nPt||\}}	|	sDt|\}}	||	v rttf | d| d| | dd| t| S dS )a   
    Attempt to download a file from GitHub release assets if it is not found locally. The function checks for the file
    locally first, then tries to download it from the specified GitHub repository release.

    Args:
        file (str | Path): The filename or file path to be downloaded.
        repo (str, optional): The GitHub repository in the format 'owner/repo'. Defaults to 'ultralytics/assets'.
        release (str, optional): The specific release version to be downloaded. Defaults to 'v8.3.0'.
        **kwargs (any): Additional keyword arguments for the download process.

    Returns:
        (str): The path to the downloaded file.

    Example:
        ```python
        file_path = attempt_download_asset("yolov8n.pt", repo="ultralytics/assets", release="latest")
        ```
    r   )SETTINGSr   r   Zweights_dirzhttps://github.com/z/releases/download)zhttp:/zhttps:/z:/r   zFound z locally at g     j@)r2   r=   r   r   N)ultralytics.utilsr   r+   r	   Zcheck_yolov5u_filenamer   stripr   rj   r   unquoterF   r   r   rK   r   r:   r
   r   GITHUB_ASSETS_REPOGITHUB_ASSETS_NAMESr   )
r=   r   releasekwargsr   rF   download_urlr2   tagr   r   r   r   attempt_download_asset  s0    
(
&r   rh   c           
   
      s   t |}|jddd dkrtH}| fddt| t| |  |  W d   q1 st0    Y  n4t| t	t fr| gn| D ]}	t
|	| d qdS )a'  
    Downloads files from specified URLs to a given directory. Supports concurrent downloads if multiple threads are
    specified.

    Args:
        url (str | list): The URL or list of URLs of the files to be downloaded.
        dir (Path, optional): The directory where the files will be saved. Defaults to the current working directory.
        unzip (bool, optional): Flag to unzip the files after downloading. Defaults to True.
        delete (bool, optional): Flag to delete the zip files after extraction. Defaults to False.
        curl (bool, optional): Flag to use curl for downloading. Defaults to False.
        threads (int, optional): Number of threads to use for concurrent downloads. Defaults to 1.
        retry (int, optional): Number of retries in case of download failure. Defaults to 3.
        exist_ok (bool, optional): Whether to overwrite existing contents during unzipping. Defaults to False.

    Example:
        ```python
        download("https://ultralytics.com/assets/example.zip", dir="path/to/dir", unzip=True)
        ```
    Tr   rh   c              
      s$   t | d | d  dkdS )Nr   rh   )r2   r   r   r   r   r   rs   r`   )r   )rH   r   r   rs   r   threadsr   r   r   <lambda>  s   zdownload.<locals>.<lambda>N)r2   r   r   r   r   r   rs   )r   r   r   mapzipr   closejoin
isinstancer+   r   )
r2   r   r   r   r   r   r   rs   poolur   r   r   download  s    

(r   )F)r7   )Tr7   T)Nr7   FT)	NNTFFr   r   FT)r   r   F)r   r   )%r(   r   r   r   	itertoolsr   Zmultiprocessing.poolr   pathlibr   urllibr   r   r{   r   r   r   r   r	   r
   r   r   r   r   r   ZGITHUB_ASSETS_STEMSr6   r@   rc   rv   cwdr   r   r   r   r   r   r   r   r   r   <module>   sv   $	



'
B&,         
g

6