
    |h@V                     :   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mZmZ d dlZd dlmZmZmZmZmZmZmZ dZ ed	D  cg c]  } d
D ]
  }d|  | d  c}} d	D  cg c]  } dD ]
  }d|  | d  c}} z   d	D  cg c]  } dD ]
  }d|  | d  c}} z   d	D  cg c]  } dD ]
  }d|  | d  c}} z   dD  cg c]  } d|  d
 c} z   dD  cg c]  } d|  d
 c} z   dD  cg c]  } d|  d
 c} z   dD  cg c]  } dD ]
  }d|  | d  c}} z   dD  cg c]  } dD ]
  }d|  | d  c}} z   dD  cg c]  } d|  d
 c} z   dD  cg c]  } d |  d
 c} z   dD  cg c]  } d!|  d
 c} z   d"D  cg c]  } d#|  d
 c} z   d$D  cg c]  } d%|  d
 c} z   d$D  cg c]  } d&|  d
 c} z   d'D  cg c]  } d(|  d
 c} z   d)D  cg c]  } d*|  d
 c} z   g d+z         Z ed, eD              ZdOd.ed/efd0ZdPd1ZdQd3ed4ed/efd5Z	 	 	 	 dRd6ed4ed/efd7Z d8 ejB                         d9d2fd:e"d;e#d<ed/efd=Z$d>e"d/ee"e"f   fd?Z%	 	 	 	 	 	 	 	 	 dSdAedBedCedDe&dEe#d6ed4efdFZ'	 	 	 dTdGe"dHe"dDed/ee"e
e"   f   fdIZ(dUdGe"dJe"d/e"fdKZ) ejB                         d2d-d-dLd@d-fdAedBedCedMe&dDe&d6efdNZ*yc c}} w c c}} w c c}} w c c}} w c c} w c c} w c c} w c c}} w c c}} w c c} w c c} w c c} w c c} w c c} w c c} w c c} w c c} w )V    N)repeat)
ThreadPool)Path)ListTuple)parserequest)LOGGERTQDMchecks	clean_urlemojis	is_onlineurl2fileultralytics/assetsnsmlx) -cls-seg-pose-obbz-oiv7yolov8z.pt)r   r   r   r   r   yolo11)r   yolo12)r   6yolov5zu.pt)r   z-sppz-tinyyolov3smlxz	-world.ptz-worldv2.ptsml)r   z-seg-pfzyoloe-v8zyoloe-11tsmceyolov9nsmblxyolov10	yolo_nas_blsam_blstsam2_zsam2.1_sxzFastSAM-lxzrtdetr-)zmobile_sam.ptzmobileclip_blt.tszyolo11n-grayscale.ptz:calibration_image_sample_data_20x128x128x3_float32.npy.zipc              #   D   K   | ]  }|j                  d       d     yw).r   N)
rpartition).0ks     Z/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/utils/downloads.py	<genexpr>r1   +   s     RS 1! 4Rs    Fcheckreturnc                 *   	 t        |       } t        j                  |       }t        |j                  |j
                  g      sJ |r2t        j                  |       5 }|j                         dk(  cddd       S y# 1 sw Y   yxY w# t        $ r Y yw xY w)a  
    Validate if the given string is a URL and optionally check 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.

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

    Examples:
        >>> valid = is_url("https://www.example.com")
        >>> valid_and_exists = is_url("https://www.example.com", check=True)
       NTF)
strr   urlparseallschemenetlocr	   urlopengetcode	Exception)urlr2   resultresponses       r0   is_urlrA   .   s    	#h$FMM6==1222% 1'')S01 11 s0   AB A:/	B :B?B B 	BBc                     |D ]W  }t        t        |       j                  |            }t        j                  d| d|        |D ]  }|j                           Y y)aB  
    Delete all specified system files in a directory.

    Args:
        path (str | Path): The directory path where the files should be deleted.
        files_to_delete (tuple): The files to be deleted.

    Examples:
        >>> from ultralytics.utils.downloads import delete_dsstore
        >>> delete_dsstore("path/to/dir")

    Notes:
        ".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)pathfiles_to_deletefilematchesfs        r0   delete_dsstorerL   I   s]        tDz''-.ivXgY78 	AHHJ	    Tcompressprogressc           	         ddl m}m}m} t	        |        t        |       } | j                         st        d|  d      | j                  d      D cg c]*  j                         st        fd|D              s), }}| j                  d      }	|r|n|}
 ||	d|
      5 t        |d	|  d
|	 dd|       D ]#  }j                  ||j                  |              % 	 ddd       |	S c c}w # 1 sw Y   |	S xY w)a  
    Zip the contents of a directory, excluding specified files.

    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.
        exclude (tuple, optional): A tuple of filename strings to be excluded.
        progress (bool, optional): Whether to display a progress bar.

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

    Examples:
        >>> 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              3   :   K   | ]  }|j                   v  y wN)namer.   xrK   s     r0   r1   z zip_directory.<locals>.<genexpr>{   s     Jl_`1TUTZTZ?Jls   .zipwzZipping  to ...rI   descunitdisableN)zipfilerQ   rR   rS   rL   r   is_dirFileNotFoundErrorrD   is_filer8   with_suffixr   writerelative_to)	directoryrN   excluderO   rQ   rR   rS   rK   files_to_zipzip_filecompressionrI   s          `    r0   zip_directoryrn   `   s   & :99YI+i[8I JKK  )s3m!qyy{sJldkJlGlAmLm$$V,H"*,
K	3	, 7hykhZs,SZ`nvjvw 	7DGGD$**956	77 O n7 Os   C0+C0 C0'>C55C?exist_okc           
        	 ddl m}m}m} t	        |       j                         r ||       s |d|  d      |t	        |       j                  } ||       5 }|j                         D 		cg c]  	t        	fd|D              s	 }
}	|
D 	ch c]  }	t	        |	      j                  d    }}	t        |      dk(  }|r|}t	        |      t        |      d   z  }n#t	        |      t	        |       j                  z  x}}|j                         rBt        |j                               r)|s't        j                   d|  d	| d
       |cddd       S t#        |
d|  dt	        |      j%                          dd|       D ]E  	dt	        	      j                  v rt        j                   d	 d       4|j'                  	|       G 	 ddd       |S c c}	w c c}	w # 1 sw Y   |S xY w)aC  
    Unzip a *.zip file to the specified path, excluding specified files.

    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 | Path): The path to the zipfile to be extracted.
        path (str | Path, optional): The path to extract the zipfile to.
        exclude (tuple, optional): A tuple of filename strings to be excluded.
        exist_ok (bool, optional): Whether to overwrite existing contents if they exist.
        progress (bool, optional): Whether to display a progress bar.

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

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

    Examples:
        >>> from ultralytics.utils.downloads import unzip_file
        >>> directory = unzip_file("path/to/file.zip")
    r   )
BadZipFilerS   
is_zipfilezFile 'z&' does not exist or is a bad zip file.Nc              3   &   K   | ]  }|v 
 y wrV    rX   s     r0   r1   zunzip_file.<locals>.<genexpr>   s     4QAQaZ4Qs      z	Skipping z  unzip as destination directory z is not empty.
Unzipping r\   r]   rI   r^   z..z Potentially insecure file path: z, skipping extraction.)rb   rq   rS   rr   r   existsparentnamelistr8   partslenrC   stemanyiterdirr
   warningr   resolveextract)rI   rG   rj   ro   rO   rq   rS   rr   zipObjrK   filestop_level_dirsunzip_as_dirextract_paths            `    r0   
unzip_filer      s   > 87JJt$46$'MNOO|Dz   
 ,&"OO-Rq4Q4Q1QRR49:q$q'--*:: >*a/L:^ 4Q 77D #'t*tDz">>D< ;;=S0NNYtf,LTFR`ab%, ,( eJtfDd9K9K9M8Nc"RY_muiuv 	,AtAw}}$!A!DZ[\NN1l+	,),6 K5 S:,6 Ks8   G,GG
GG/BGA6G
GG(z(https://ultralytics.com/assets/coco8.zipg      ?r>   sfhardc                    ddl }	 |j                  |       }|j                  dk  s$J d|  d|j                   d|j                          	 dt        |j                  j                  d	d            z  }fd
t        j                  |      D        \  }}}	||z  |	k  ryd|	dd||z  dd||z  |	z
  dd}
|rt        |
      t        j                  |
       y# t        $ r Y yw xY w)a  
    Check if there is sufficient disk space to download and store a file.

    Args:
        url (str, optional): The URL to the file.
        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.
        hard (bool, optional): Whether to throw an error or not on insufficient disk space.

    Returns:
        (bool): True if there is sufficient disk space, False otherwise.
    r   Ni  zURL error for :  Ti   @Content-Lengthc              3   (   K   | ]	  }|z    y wrV   rt   )r.   rY   gibs     r0   r1   z#check_disk_space.<locals>.<genexpr>   s     BQSBs   z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
   r   )r>   rG   r   r   r   rdatatotalusedfreetextr   s              @r0   check_disk_spacer      s   $ MM#}}s"VnSEAMM?!AHH:$VV"
 Cqyy}}-q12S8DB&*;*;D*ABE4by4 (Szr	# Gby4',,T	V 	 $
NN4'  s   AC 	C('C(linkc                 B   ddl }| j                  d      d   j                  dd      d   }d| }d}|j                         5 }|j                  |d      }d	t	        |j
                  j                               v rt        t        d
|  d            |j                  j                         D ]  \  }}|j                  d      s|d| z  }! |j                  j                  d      x}	rt        j                  d|	      d   }ddd       ||fS # 1 sw Y   ||fS xY w)ay  
    Retrieve 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:
        url (str): Direct download URL for the Google Drive file.
        filename (str | None): Original filename of the Google Drive file. If filename extraction fails, returns None.

    Examples:
        >>> 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)
    r   Nz/d/ru   z/viewz/https://drive.google.com/uc?export=download&id=T)streamzquota exceededui   ❌  Google Drive file download quota exceeded. Please try again later or download this file manually at r,   download_warningz	&confirm=zcontent-dispositionzfilename="(.+)")r   splitSessionr   r6   contentlowerConnectionErrorr   cookiesitems
startswithr   refindall)
r   r   file_id	drive_urlfilenamesessionr@   r/   vcds
             r0   get_google_drive_file_infor      sD     jj"((!4Q7GA'KIH 
			 <w;;y;6s8#3#3#9#9#;<<!PPTvUVX  $$**, 	-DAq||./y_,		- !!%%&;<<2<zz"3R8;H< h< hs   BDA DD   unzipdeletecurlretry	min_bytesc
                    | j                  d      }
|
rt        |       \  } }t        |xs d      |xs t        |       z  }dt	        |       vr&t        |       j                         rt        |       }n|j                         s|
r| n
t        |       j                  dd      }d| d| d}t        j                  | d	       |j                  j                  d
d
       t        | |j                         t        j                  d      }t        |dz         D ]R  }	 |s|dkD  rD|rBd|	 z  }t!        j"                  ddd| d| d|ddddg
      j$                  }|dk(  sJ d|        d}|dk(  r#t&        j(                  j+                  | ||	       nt-        j.                  |       5 }t1        t3        |j5                  dd            ||	 dd
d      5 }t7        |d      5 }|D ]-  }|j9                  |       |j;                  t=        |             / 	 d d d        d d d        d d d        |j?                         r/|jA                         jB                  |kD  r n|jE                          U |r|j?                         r|jP                  d'v rdd(l)m*} |xs |j                  jW                         } ||      rtY        ||||	)      }nW|jP                  d*v rIt        j                  d+| d,| d	       t!        j"                  d-|jP                  d.k(  rd/nd0|d1|gd
2       |r|jE                          |S |S # 1 sw Y   %xY w# 1 sw Y   *xY w# 1 sw Y   /xY w# tF        $ rs}|dk(  r#tI               stK        tM        d!| d"            |||k\  rtK        tM        d!| d#            |t        jN                  d$|dz    d%| d&| d	       Y d }~d }~ww xY w)3a  
    Download 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 | Path, 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.
        delete (bool, optional): Whether to delete the downloaded file after unzipping.
        curl (bool, optional): Whether to use curl command line tool for downloading.
        retry (int, optional): The number of times to retry the download in case of failure.
        min_bytes (float, optional): The minimum number of bytes that the downloaded file should have, to be considered
            a successful download.
        exist_ok (bool, optional): Whether to overwrite existing contents during unzipping.
        progress (bool, optional): Whether to display a progress bar during the download.

    Returns:
        (Path | str): The path to the downloaded file or extracted directory.

    Examples:
        >>> 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 ''r]   Tparentsro   )rG   r   ru   r   sSz-#-Lz-oz--retry3z-CzCurl return value torch)rO   r   Bi   )r   r_   ra   r`   
unit_scaleunit_divisorwbNu   ❌  Download failure for z. Environment is not online.z. Retry limit reached.zDownload failure, retrying /r   >   r   .gz.tarrZ   )rr   )rI   rG   ro   rO   >   r   r   rv   r\   tarr   xfxfzz--directory)r2   )-r   r   r   r   r6   re   r   replacer
   rE   rx   mkdirr   r   whichrange
subprocessrun
returncoder   hubdownload_url_to_filer	   r;   r   r   	getheaderopenrg   updater{   rw   statst_sizerF   r=   r   r   r   r   suffixrb   rr   r   r   )r>   rI   dirr   r   r   r   r   ro   rO   gdriverK   urir_   curl_installedisr   methodr@   pbarf_openedr   err   	unzip_dirs                             r0   safe_downloadr     s   L ^^78F.s3	TSZCD1HSM2ACHc!2!2!4IYY[s)C.99M-
 cU%s!,tfCL!	td3188,f-uqy! !	WA WAE~H-A"!AhT1iY\^bdg'hittA6;%7s#;;6$F(		66sA6Q$__S1 ;Xt"%h&8&89I1&M"N!%(0L!$'+)-@ ; "!%a ;(,4 !;D$,NN4$8$(KKD	$:!;;; ; 88:vvx'')3HHJ7!	WF ,G G&_AHH--/	a="	HW_`IXX(KK*QCtI;c:;NNE188v+=45!]\efnrsHHJH9; ;; ; ; ;"  W6)+)&3McURn1o*pqwxx%Z)&3McURh1i*jkqrr!<QUG1UG1SEQTUVVWsh   !B
M"+,MM$3L;	M M(5M"M";M MMMM	M""	O+A(OOrepoversionc                    ddl }|dk7  rd| }d|  d| }|j                  |      }|j                  dk7  r"|j                  dk7  r|r|j                  |      }|j                  dk7  r6t	        j
                  d	| d
|j                   d|j                          dg fS |j                         }|d   |d   D cg c]  }|d   	 c}fS c c}w )al  
    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'.
        version (str, optional): The release version to fetch assets from.
        retry (bool, optional): Flag to retry the request in case of a failure.

    Returns:
        tag (str): The release tag.
        assets (List[str]): A list of asset names.

    Examples:
        >>> tag, assets = get_github_assets(repo="ultralytics/assets", version="latest")
    r   Nlatestztags/zhttps://api.github.com/repos/z
/releases/r5   zrate limit exceededz GitHub assets check failure for r   r   r   tag_nameassetsrW   )r   r   r   r   r
   r   json)r   r   r   r   r>   r   r   rY   s           r0   get_github_assetsr     s    , ('#)$z'
CCSA}},A AeLL}}9#bqQRQYQYPZ[\2v668D
h@Aai@@@@s   9C	releasec                    ddl m} t        |       } t        j                  |       } t        | j                         j                  dd            } | j                         rt        |       S |d   | z  j                         rt        |d   | z        S t        t        j                  t        |                   j                  }d| d}t        |       j                  d      rt        |       j                  d	d
      }t        |      } t        |       j                         r/t        j                   dt#        |       d|         t        |       S t%        d|| dd| t        |       S |t&        k(  r*|t(        v r"t%        d| d| d| | dd| t        |       S t+        ||      \  }}	|	st+        |      \  }}	||	v rt%        d| d| d| | dd| t        |       S )aS  
    Attempt to download a file from GitHub release assets if it is not found locally.

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

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

    Examples:
        >>> file_path = attempt_download_asset("yolo11n.pt", repo="ultralytics/assets", release="latest")
    r   )SETTINGSr   r   weights_dirzhttps://github.com/z/releases/download)zhttp:/zhttps:/z:/r   zFound z locally at g     j@)r>   rI   r   r   rt   )ultralytics.utilsr   r6   r   check_yolov5u_filenamer   stripr   rw   r   unquoterW   r   r   re   r
   rE   r   r   GITHUB_ASSETS_REPOGITHUB_ASSETS_NAMESr   )
rI   r   r   kwargsr   rW   download_urlr>   tagr   s
             r0   attempt_download_assetr     s     + t9D((.D

$$S"-.D{{}4y
=
!D
(	0	0	28M*T122 EMM#d),-22,TF2DEt9 56d)##D%0CD>DDz!!#fYs^$4LGH 4y J#DCJ6J 4y ''D4G,Geay$@tWZe^de 4y ,D':KC/5Vv~e\N!C5$"@tWZe^de4yrM   ru   threadsc           
         t        |      }|j                  dd       dkD  rbt              5 }|j                  fdt	        | t        |                   |j                          |j                          ddd       yt        | t        t         f      r| gn| D ]  }	t        |	|        y# 1 sw Y   yxY w)a  
    Download files from specified URLs to a given directory.

    Supports concurrent downloads if multiple threads are specified.

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

    Examples:
        >>> download("https://ultralytics.com/assets/example.zip", dir="path/to/dir", unzip=True)
    Tr   ru   c                 <    t        | d   | d   dk        S )Nr   ru   )r>   r   r   r   r   r   ro   rO   )r   )rY   r   r   ro   r   r  r   s    r0   <lambda>zdownload.<locals>.<lambda>  s0    -!!!%$\	 rM   N)r>   r   r   r   r   r   ro   )r   r   r   mapzipr   closejoin
isinstancer6   r   )
r>   r   r   r   r   r  r   ro   poolus
     ``````  r0   downloadr    s    8 s)CIIdTI*{  	DHH	 	 C% JJLIIK	 	" %S3+6#C 	qAaSf4W\gop	q#	 	s   AB??C)F)z	.DS_Store__MACOSX)Tr  T)Nr  FT)	NNTFFr   g      ?FT)r   r   F)r   zv8.3.0)+r   r   r   	itertoolsr   multiprocessing.poolr   pathlibr   typingr   r   urllibr   r	   r   r   r
   r   r   r   r   r   r   r   	frozensetr   GITHUB_ASSETS_STEMSboolrA   rL   rn   r   cwdr6   floatr   r   r   r   r   r   r  )r/   r   
resolutions   000r0   <module>r     s   
    +   !  Z Z Z * &-k<jk&vaSkk(/d1>cdFs6(#dde(/D1eDFs6(#DDE .5QyQs:,d#Q#QR "77As$7	8
 '--s)-. )//1s+/0 +0RQ>QRF!VHC R RS +0RQ>QRF!VHC R RS !((1s#(	) "**A3*
+ $))a1#S)* ##aS}#$  &&!qc~&' "((A3() #''Q!C'(  "&&A3&!'"# 2  R>QRR t  6."t "ae "qu "N 
%B 	B
 B 
BL :		*	* 	* 	*
 
*Z%S %U38_ %T 
f 	f
 f f f f f fT %"A
"A"A "A 3S	>	"AJ0s 0C 0il 0j 	
1q 1q 	1q
 1q 1q 1q 1q[ ldDQ7-/RR(*)#&('&sf   K
,KK,KK
 K
5K$
K)+K/
K5
K:
4K?
	L
L	
3L
L
L
