o
    Vhz>                     @   s  U 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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mZmZmZmZmZmZmZmZmZ d dlmZ d dlZd dlZd dlmZ ddl m!Z!m"Z" dZ#d\d	e$d
ee$ej%f de&ddfddZ'd]dee$ej%f de&de$fddZ(dee$ej%f de$dede)fddZ*d^dee$ej%f dee$ de)fddZ+d_d	e$de&de$fddZ,d	e$dee$ fddZ-			d`d	e$dee$ej%f d
eee$ej%f  dee$ d e&ddfd!d"Z.dadee$ej%f d$e)dee$ fd%d&Z/dadee$ej%f d'e$d$e)dee$ fd(d)Z0		dbd*e$dee$ej%f d
eee$ej%f  dee$ fd+d,Z1d-ee$ej%f d.ee$ej%f d/ee$ ddfd0d1Z2ej3ej4d2Z5ee$e&f e6d3< d-ee$ej%f d.ee$ej%f d/ee$ ddfd4d5Z7e2e7d6Z8ee$eee$ej%f ee$ej%f ee$ gdf f e6d7< e j9ej9ej9d8Z:ee$ed9ef f e6d:< d;d;d<d=Z;ee$eee$ ee$ f f e6d>< d?ee$ej%f dee$ee$ ee$ f fd@dAZ<		#dcd-ee$ej%f d.eee$ej%f  dBe)dej%fdCdDZ=		#dcd-ee$ej%f d.eee$ej%f  dBe)dee$ej%f fdEdFZ>				#ddd	e$dGee$ej%f dHeee$ej%f  d
eee$ej%f  dee$ dBe)ddfdIdJZ?dKede$fdLdMZ@edNe$eAZB			dedOeBdPee$ dQeeeB  dRee$ deBf
dSdTZCdfdUee$ej%f dVe&dejDfdWdXZEdYejFdejFfdZd[ZGdS )g    N)
AnyCallableDictIOIterableListOptionalTupleTypeVarUnion)urlparse)tqdm   )#_download_file_from_remote_location_is_remote_location_availablezpytorch/vision   urlfilename
chunk_sizereturnc              
   C   s   t jt jj| dtidX}t|d:}t|jddd"}|| }r8|	| |
t| || }s%W d    n1 sBw   Y  W d    n1 sQw   Y  W d    d S W d    d S 1 siw   Y  d S )N
User-AgentheaderswbBT)totalunit
unit_scale)urllibrequesturlopenRequest
USER_AGENTopenr   lengthreadwriteupdatelen)r   r   r   responsefhpbarchunk r-   N/var/www/vscode/kcb/lib/python3.10/site-packages/torchvision/datasets/utils.py_urlretrieve   s   
 "r/      fpathc                 C   s   t jdkrtjdd}nt }t| d(}|| }r3|| || }sW d    | S W d    | S 1 s@w   Y  | S )N)   	   F)usedforsecurityrb)sysversion_infohashlibmd5r#   r%   r'   	hexdigest)r1   r   r9   fr,   r-   r-   r.   calculate_md5#   s   



r<   r9   kwargsc                 K   s   |t | fi |kS N)r<   )r1   r9   r=   r-   r-   r.   	check_md51   s   r?   c                 C   s&   t j| sdS |d u rdS t| |S )NFT)ospathisfiler?   )r1   r9   r-   r-   r.   check_integrity5   s
   
rC   r2   max_hopsc              	   C   s   | }dt d}t|d D ]6}tjtjj| |d }|j| ks&|jd u r1| W  d      S |j} W d    n1 s>w   Y  qtd| d| d|  d)	NHEAD)Methodr      r   zRequest to z
 exceeded z( redirects. The last redirect points to .)r"   ranger   r   r    r!   r   RecursionError)r   rD   initial_urlr   _r)   r-   r-   r.   _get_redirect_url=   s   
rM   c                 C   sB   t | }td|jd u rd S td|j}|d u rd S |dS )Nz(drive|docs)[.]google[.]comz/file/d/(?P<id>[^/]*)id)r   rematchnetlocrA   group)r   partsrP   r-   r-   r.   _get_google_drive_file_idM   s   
rT   rootmax_redirect_hopsc              
   C   s  t j|}|st j| }t t j||}t j|dd t||r&dS t r/t	||  nIt
| |d} t| }|durDt||||S zt| | W n, tjjtfyw } z| dd dkrk| dd} t| | n|W Y d}~nd}~ww t||std	dS )
a  Download a file from a url and place it in root.

    Args:
        url (str): URL to download file from
        root (str): Directory to place downloaded file in
        filename (str, optional): Name to save the file under. If None, use the basename of the URL
        md5 (str, optional): MD5 checksum of the download. If None, do not check
        max_redirect_hops (int, optional): Maximum number of redirect hops allowed
    Texist_okN)rD      httpszhttps:zhttp:File not found or corrupted.)r@   rA   
expanduserbasenamefspathjoinmakedirsrC   r   r   rM   rT   download_file_from_google_driver/   r   errorURLErrorOSErrorreplaceRuntimeError)r   rU   r   r9   rV   r1   file_ider-   r-   r.   download_urlZ   s4   

ri   Fprefixc                    sB   t j   fddt  D }|du r fdd|D }|S )a  List all directories at a given root

    Args:
        root (str): Path to directory whose folders need to be listed
        prefix (bool, optional): If true, prepends the path to each result, otherwise
            only returns the name of the directories found
    c                    s&   g | ]}t jt j |r|qS r-   )r@   rA   isdirr_   .0prU   r-   r.   
<listcomp>   s   & zlist_dir.<locals>.<listcomp>Tc                       g | ]	}t j |qS r-   r@   rA   r_   rm   dro   r-   r.   rp          r@   rA   r\   listdir)rU   rj   directoriesr-   ro   r.   list_dir   s
   ry   suffixc                    sD   t j   fddt  D }|du r  fdd|D }|S )a  List all files ending with a suffix at a given root

    Args:
        root (str): Path to directory whose folders need to be listed
        suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png').
            It uses the Python "str.endswith" method and is passed directly
        prefix (bool, optional): If true, prepends the path to each result, otherwise
            only returns the name of the files found
    c                    s0   g | ]}t jt j |r|r|qS r-   )r@   rA   rB   r_   endswithrl   rU   rz   r-   r.   rp      s   0 zlist_files.<locals>.<listcomp>Tc                    rq   r-   rr   rs   ro   r-   r.   rp      ru   rv   )rU   rz   rj   filesr-   r|   r.   
list_files   s
   
r~   rg   c                 C   s   zddl }W n ty   tdw tj|}|s| }ttj||}tj|dd t	||r4dS |j
| |dtd t	||sFtddS )	af  Download a Google Drive file from  and place it in root.

    Args:
        file_id (str): id of file to be downloaded
        root (str): Directory to place downloaded file in
        filename (str, optional): Name to save the file under. If None, use the id of the file.
        md5 (str, optional): MD5 checksum of the download. If None, do not check
    r   Nz`To download files from GDrive, 'gdown' is required. You can install it with 'pip install gdown'.TrW   F)rN   outputquiet
user_agentr[   )gdownModuleNotFoundErrorrf   r@   rA   r\   r^   r_   r`   rC   downloadr"   )rg   rU   r   r9   r   r1   r-   r-   r.   ra      s$   

ra   	from_pathto_pathcompressionc                 C   sR   t | |rd|dd   nd}|| W d    d S 1 s"w   Y  d S )Nzr:rG   r)tarfiler#   
extractall)r   r   r   tarr-   r-   r.   _extract_tar   s   $"r   ).bz2.xz_ZIP_COMPRESSION_MAPc                 C   sN   t j| d|r
t| nt jd}|| W d    d S 1 s w   Y  d S )Nr   )r   )zipfileZipFiler   
ZIP_STOREDr   )r   r   r   zipr-   r-   r.   _extract_zip   s   "r   ).tarz.zip_ARCHIVE_EXTRACTORS)r   .gzr   ._COMPRESSED_FILE_OPENERS)r   r   )r   r   )z.tbzz.tbz2z.tgz_FILE_TYPE_ALIASESfilec                 C   s   t | j}|std|  d|d }|tv r |gt| R S |tv r)||dfS |tv rGt|dkrB|d }|tv rB|| ||fS |d|fS tt	tt	tB t	tB }td| d| d	)
a  Detect the archive type and/or compression of a file.

    Args:
        file (str): the filename

    Returns:
        (tuple): tuple of suffix, archive type, and compression

    Raises:
        RuntimeError: if file has no suffix or suffix is not supported
    zFile 'zP' has no suffixes that could be used to detect the archive type and compression.NrG   z&Unknown compression or archive type: 'z'.
Known suffixes are: 'z'.)
pathlibPathsuffixesrf   r   r   r   r(   sortedset)r   r   rz   suffix2valid_suffixesr-   r-   r.   _detect_file_type   s$   


r   remove_finishedc           	   	   C   s   t | \}}}|std| d|du r'tt| ||dur#|nd}t| }|| d$}t|d}|	|
  W d   n1 sHw   Y  W d   n1 sWw   Y  |rct|  t|S )a  Decompress a file.

    The compression is automatically detected from the file name.

    Args:
        from_path (str): Path to the file to be decompressed.
        to_path (str): Path to the decompressed file. If omitted, ``from_path`` without compression extension is used.
        remove_finished (bool): If ``True``, remove the file after the extraction.

    Returns:
        (str): Path to the decompressed file.
    z*Couldn't detect a compression from suffix rH   N r5   r   )r   rf   r   r   r@   r^   re   r   r#   r&   r%   remove)	r   r   r   rz   archive_typer   compressed_file_openerrfhwfhr-   r-   r.   _decompress%  s   $ 

r   c           	   	      s   dt jdttt jf f fdd}|du rtj }t \}}}|s<t tj	|tj
 |d|d}||S t| }| || |rMt  |t |S )aD  Extract an archive.

    The archive type and a possible compression is automatically detected from the file name. If the file is compressed
    but not an archive the call is dispatched to :func:`decompress`.

    Args:
        from_path (str): Path to the file to be extracted.
        to_path (str): Path to the directory the file will be extracted to. If omitted, the directory of the file is
            used.
        remove_finished (bool): If ``True``, remove the file after the extraction.

    Returns:
        (str): Path to the directory the file was extracted to.
    ret_pathr   c                    s   t  tr
t| S | S r>   )
isinstancestrr@   r^   )r   r   r-   r.   path_or_str]  s   

z$extract_archive.<locals>.path_or_strNr   )r   )r   r   r   r   r@   rA   dirnamer   r   r_   r]   re   r   r   )	r   r   r   r   rz   r   r   r   	extractorr-   r   r.   extract_archiveI  s    "
r   download_rootextract_rootc                 C   sT   t j|}|d u r|}|st j| }t| ||| t j||}t||| d S r>   )r@   rA   r\   r]   ri   r_   r   )r   r   r   r   r9   r   archiver-   r-   r.   download_and_extract_archivey  s   r   iterablec                 C   s   dd dd | D  d S )N'z', 'c                 S   s   g | ]}t |qS r-   )r   )rm   itemr-   r-   r.   rp     s    z#iterable_to_str.<locals>.<listcomp>)r_   )r   r-   r-   r.   iterable_to_str  s   r   Tvalueargvalid_values
custom_msgc                 C   s   t | ts|d u rd}nd}|jt| |d}t||d u r!| S | |vr?|d ur/|}t|d}|j| |t|d}t|| S )Nz'Expected type str, but got type {type}.z:Expected type str for argument {arg}, but got type {type}.)typer   zPUnknown value '{value}' for argument {arg}. Valid values are {{{valid_values}}}.)r   r   r   )r   r   formatr   
ValueErrorr   )r   r   r   r   msgr-   r-   r.   verify_str_arg  s    
r   	file_nameslice_channelsc                 C   s  t | dL}|  }|dvrtdtd| }|s"tddd | D \}}t|  }|dk r?d	}| }nd
}t	j
||d d}	W d   n1 sTw   Y  |dkr_dnd}
|	|||
ddd}	t	j|	dd}	|	d|ddddf }	|	t	jS )aD  Read file in .pfm format. Might contain either 1 or 3 channels of data.

    Args:
        file_name (str): Path to the file.
        slice_channels (int): Number of channels to slice out of the file.
            Useful for reading different data formats stored in .pfm files: Optical Flows, Stereo Disparity Maps, etc.
    r5   )   PFs   PfzInvalid PFM files   ^(\d+)\s(\d+)\s$zMalformed PFM header.c                 s   s    | ]}t |V  qd S r>   )int)rm   dimr-   r-   r.   	<genexpr>  s    z_read_pfm.<locals>.<genexpr>r   <>r;   )dtypeNr   r2   rG   r   )axis)r#   readlinerstripr   rO   rP   	Exceptiongroupsfloatnpfromfilereshape	transposeflipastypefloat32)r   r   r;   header	dim_matchwhscaleendiandatapfm_channelsr-   r-   r.   	_read_pfm  s(   	r   tc                 C   sN   |   tjjg | j|  R  djg | jd d dR  | jS )Nr   )
contiguousviewtorchuint8shapeelement_sizer   r   )r   r-   r-   r.   _flip_byte_order  s   Lr   )r   )r0   r>   )r2   )NNr2   )F)NN)NF)NNNF)NNN)r   )Hbz2gzipr8   lzmar@   os.pathr   rO   r6   r   r   urllib.errorurllib.requestr   typingr   r   r   r   r   r   r   r	   r
   r   urllib.parser   numpyr   r   torch.utils.model_zoor   _internally_replaced_utilsr   r   r"   r   r   r   r/   r<   boolr?   rC   rM   rT   ri   ry   r~   ra   r   	ZIP_BZIP2ZIP_LZMAr   __annotations__r   r   r#   r   r   r   r   r   r   r   bytesr   r   ndarrayr   Tensorr   r-   r-   r-   r.   <module>   s(  
 0&"$&
&5*
%


<&.-
&
3


$$