
    FPhE              
          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  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
 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gz   ZeD  cg c]  }  e	|       j2                   c} Zd(dZd)dZd*dZd+dZd,d Zd! Z 	 	 	 	 	 	 	 	 d-d#Z!d.d$Z"d/d%Z# e	jH                         dddd&d"fd'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 )0    N)repeat)
ThreadPool)Path)parserequest)LOGGERTQDMchecks	clean_urlemojis	is_onlineurl2fileultralytics/assetsnsmlx) z-clsz-segz-poseyolov8z.pt)r   6yolov5zu.pt)r   z-sppz-tinyyolov3sml	yolo_nas_blsam_sxzFastSAM-lxzrtdetr-zmobile_sam.ptTc                 z   t        j                  t              5  t        |       } t	        j
                  |       }t        |j                  |j                  g      sJ |r;t        j                  |       5 }|j                         dk(  cddd       cddd       S 	 ddd       y# 1 sw Y   xY w# 1 sw Y   yxY w)z/Check if string is URL and check if URL exists.   NTF)
contextlibsuppress	Exceptionstrr   urlparseallschemenetlocr   urlopengetcode)urlcheckresultresponses       fC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/utils/downloads.pyis_urlr-      s    			Y	'#h$FMM6==1222%'')S0 &% 
(	'  
(	'
 &% 
( s*   AB15B%	B1B1%B.	*B11B:c                     |D ]W  }t        t        |       j                  |            }t        j                  d| d|        |D ]  }|j                           Y y)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)pathfiles_to_deletefilematchesfs        r,   delete_dsstorer8   +   sS    (  tDz''-.ivXgY78AHHJ       c           	         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  
    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              3   :   K   | ]  }|j                   v  y wN)name.0xr7   s     r,   	<genexpr>z zip_directory.<locals>.<genexpr>c   s      Jldk_`1TUTZTZ?dks   .zipwzZipping  to ...r5   descunitdisableN)zipfiler;   r<   r=   r8   r   is_dirFileNotFoundErrorr0   is_filer#   with_suffixr	   writerelative_to)	directorycompressexcludeprogressr;   r<   r=   r7   files_to_zipzip_filecompressionr5   s          `    r,   zip_directoryr\   F   s    * :99YI+i[8I JKK  )s3m3!qyy{sJldkJlGlA3Lm$$V,H"*,
K	3	,hykhZs,SZ`nvjvwDGGD$**956 x 
- O n 
- Os   C0+C0 C0'>C55C?Fc           
        	 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kD  s|
d   j                  d      s$t	        |      t	        |       j                  z  x}}n|}t	        |      t        |      d   z  }|j                         rBt        |j                               r)|s't!        j"                  d	|  d
| d       |cddd       S t%        |
d|  dt	        |      j'                          dd|       D ]  	|j)                  	|        	 ddd       |S c c}	w c c}	w # 1 sw Y   |S xY w)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   )
BadZipFiler=   
is_zipfilezFile 'z&' does not exist or is a bad zip file.Nc              3   &   K   | ]  }|v 
 y wr@    rB   s     r,   rE   zunzip_file.<locals>.<genexpr>   s     4QAQaZs      /u   WARNING ⚠️ Skipping z  unzip as destination directory z is not empty.
Unzipping rH   rI   r5   rJ   )r3   )rN   r^   r=   r_   r   existsparentnamelistr#   partslenendswithstemr/   anyiterdirr   warningr	   resolveextract)r5   r3   rW   exist_okrX   r^   r=   r_   zipObjr7   filestop_level_dirsextract_paths            `   r,   
unzip_filerv   m   s   8 87JJt$46$'MNOO|Dz   
&"OO-R-q4Q4Q1Q-R49:Eq$q'--*E:~"%(*;*;C*@"&t*tDz">>D<L:^ 4Q 77D ;;=S0NN5dV;[\`[aaopq 
  eJtfDd9K9K9M8Nc"RY_muiuvANN1<N0 w! 
& K% S: 
& Ks8   G ,F6F6
G F;/B,G %AG 6
G  G
c                   	 	 t        j                  |       }|j                  dk  s$J d|  d|j                   d|j                          	 d	t        |j                  j                  dd            	z  }	fd	t        j                  d
      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. Defaults to 'https://ultralytics.com/assets/coco128.zip'.
        sf (float, optional): Safety factor, the multiplier for the required free space. Defaults to 2.0.
        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   (   K   | ]	  }|z    y wr@   ra   )rC   rD   gibs     r,   rE   z#check_disk_space.<locals>.<genexpr>   s     A*@QS*@s   rc   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   rn   )
r(   sfhardrdatatotalusedfreetextr|   s
            @r,   check_disk_spacer      s   MM#}}s"VnSEAMM?!AHH:$VV"
 Cqyy}}-q12S8DA&*;*;C*@AE4by4 ;4*F4RT9UX/ Z"9t+C00XZD$
NN4!  s   AC 	C('C(c                 @   | j                  d      d   j                  d      d   }d| }d}t        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      }|rt        j                  d|      d   }ddd       ||fS # 1 sw Y   ||fS xY w)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/rb   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 .download_warningz	&confirm=zcontent-dispositionzfilename="(.+)")splitr}   Sessionr   r!   contentlowerConnectionErrorr   cookiesitems
startswithr   refindall)	linkfile_id	drive_urlfilenamesessionr+   kvcds	            r,   get_google_drive_file_infor      s6   & jj"((1!4GA'KIH 
			w;;y;6s8#3#3#9#9#;<<! SSWRXXY[ \] ] $$**,DAq||./y_,	 - !!"78zz"3R8;H 
 h 
 hs   BDA DD   c	                 n   | j                  d      }	|	rt        |       \  } }|r||	r|n
t        |       z  n
t        |      }
dt	        |       vr&t        |       j                         rt        |       }
n|
j                         s|s	|sJ d       d|	r| n
t        |        d|
 d}t        j                  | d       |
j                  j                  dd	       t        |        t        |d
z         D ]P  }	 |s|dkD  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 }t+        t-        |j/                  dd            || ddd      5 }t1        |
d      5 }|D ]-  }|j3                  |       |j5                  t7        |             / 	 ddd       ddd       ddd       |
j9                         r/|
j;                         j<                  |kD  r n|
j?                          S |r|
j9                         r|
jJ                  d$v rdd%l&m'} |xs |
j                  } ||
      rtQ        |
||&      }ne|
jJ                  d'v rWt        j                  d(|
 d)|jS                          d       t        j                  d*|
jJ                  d+k(  rd,nd-|
d.|gd/       |r|
j?                          |S yyy# 1 sw Y   %xY w# 1 sw Y   *xY w# 1 sw Y   /xY w# t@        $ rs}|dk(  r#tC               stE        tG        d|  d            |||k\  rtE        tG        d|  d             |t        jH                  d!|d
z    d"| d#|  d       Y d}~d}~ww xY w)0a  
    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.
        progress (bool, optional): Whether to display a progress bar during the download. Default: True.
    zhttps://drive.google.com/://z!dir or file required for downloadzDownloading z to ''rI   Tparentsrq   rb   r   sScurlz-#-Lz-oz--retry3z-CzCurl return value torch)rX   rz   Bi   )r   rK   rM   rL   
unit_scaleunit_divisorwbNu   ❌  Download failure for z. Environment is not online.z. Retry limit reached.u"   ⚠️ Download failure, retrying rc   ry   )r   rF   .tar.gz)r_   )r5   r3   rX   )r   r   rd   rH   tarr   xfxfzz--directory)r)   )*r   r   r   r   r!   rQ   r   r   r1   rf   mkdirr   range
subprocessrun
returncoder   hubdownload_url_to_filer   r&   r	   r   	getheaderopenrS   updateri   re   statst_sizer2   r    r   r   r   rn   suffixrN   r_   rv   ro   )r(   r5   dirunzipdeleter   retry	min_bytesrX   gdriver7   rK   isr   methodr+   pbarf_openedr   er_   	unzip_dirs                          r,   safe_downloadr      sx   8 ^^78F.s3	T58vt8C=1d4jACHc!2!2!4IYY[d???{Vc3@aSJtfCL!	td3uqy!A^1q5H-A"!AhT1iY\^bdg'hittA6;%7s#;;6$F(		66sA6Q$__S1Xt#hN`N`aqstNuJvIMPXLILOSQU@W
 [_!%a(,4D$,NN4$8$(KKD	$: -5 "/@W1 88:vvx'')3HHJ3 "B ,G G&O188	a="	HMIXX(KK*QCtI,=,=,?+@DENNE188v+=45!]\efnrsHHJ !Hu! "/@W @W11  ^6)+)&3McURn1o*pqwxx%Z)&3McURh1i*jkqrr!CAE7!E7RSTWSXX[\]]^sh   9BL8,L+-L:3L	.L6L+>5L85L8LLL(#L++L5	0L88	N4A(N//N4c                    |dk7  rd| }d|  d| }t        j                  |      }|j                  dk7  r&|j                  dk7  r|rt        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 )zKReturn GitHub repo tag and assets (i.e. ['yolov8n.pt', 'yolov8s.pt', ...]).latestztags/zhttps://api.github.com/repos/z
/releases/r   zrate limit exceededu'   ⚠️ GitHub assets check failure for rx   ry   r   tag_nameassetsrA   )r}   r   r   r   r   rn   json)repoversionr   r(   r   r   rD   s          r,   get_github_assetsr   H  s    ('#)$z'
CCSA}},A AeLL}}@RVWXYX`X`Wabc2v668D
h@Aai@@@@s   =Cc                    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                  }t        |       j                  d      rt        |       j                  dd      }t        |      } t        |       j                         r/t        j                   d	t#        |       d
|         t        |       S t%        || d       t        |       S |t&        k(  r*|t(        v r"t%        d| d| d| | d       t        |       S t+        ||      \  }}|st+        |      \  }}||v rt%        d| d| d| | d       t        |       S )zv
    Attempt file download from GitHub release assets if not found locally.

    release = 'latest', 'v6.2', etc.
    r   )SETTINGSr   r   weights_dir)zhttp:/zhttps:/z:/r   zFound z locally at g     j@)r(   r5   r   zhttps://github.com/z/releases/download/rc   )ultralytics.utilsr   r!   r
   check_yolov5u_filenamer   stripreplacere   r   unquoterA   r   r   rQ   r   r1   r   r   GITHUB_ASSETS_REPOGITHUB_ASSETS_NAMESr   )r5   r   releaser   rA   r(   tagr   s           r,   attempt_download_assetr   W  s    + t9D((.D

$$S"-.D{{}4y
=
!D
(	0	0	28M*T122 EMM#d),-22t9 56d)##D%0CD>DDz!!#fYs^$4LGH 4y #DC@ 4y ''D4G,G 3D69LWIUVW[V\]dhtwx 4y ,D':KC/5Vv~$7v=PQTPUUVW[V\"]dhtwx4yr9   rb   c           
         t        |      }|j                  dd       dkD  rat              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)zJDownloads and unzips files concurrently if threads > 1, else sequentially.Tr   rb   c           
      :    t        | d   | d   dk        S )Nr   rb   )r(   r   r   r   r   r   rX   )r   )rD   r   r   r   threadsr   s    r,   <lambda>zdownload.<locals>.<lambda>  s*    -!!A$eFUZelpqeqsr9   N)r(   r   r   r   r   r   )r   r   r   mapzipr   closejoin
isinstancer!   r   )	r(   r   r   r   r   r   r   poolus	     `````  r,   downloadr     s    
s)CIIdTI*{ DHHsC%' JJLIIK !  %S3+6#C?AaSf4W\] @ ! s   AB<<C)T)z	.DS_Store__MACOSX)Tr   T)Nr   FT)z*https://ultralytics.com/assets/coco128.zipg      ?T)NNTFFr   g      ?T)r   r   F)r   zv0.0.0)&r   r   r   r   	itertoolsr   multiprocessing.poolr   pathlibr   urllibr   r   r}   r   r   r   r	   r
   r   r   r   r   r   r   rk   GITHUB_ASSETS_STEMSr-   r8   r\   rv   r   r   r   r   r   cwdr   )r   r   
resolutions   000r,   <module>r     s    	    +  !   Z Z Z * 8?l1NkFs6(#.Nk.l=DaWW`s:,d3W`3Wab1FG1FAs$'1FGH 4995a1#S)59: /33daS}d3	4
 377$Q!C($78 266A3'67 ''(  .AA-@tAw||-@A 
6$N7tD$P UpA%P dhhjUPQYZ ^Y maG9376As0   E*E	E$E)3E.E3E87E=