U
    h?                  	   @   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#dRe$ee$ej%f e&dd	d
dZ'dSee$ej%f e&e$dddZ(ee$ej%f e$ee)dddZ*dTee$ej%f ee$ e)dddZ+dUe$e&e$dddZ,e$ee$ dddZ-dVe$ee$ej%f eee$ej%f  ee$ e&ddddZ.dWee$ej%f e)ee$ d!d"d#Z/dXee$ej%f e$e)ee$ d$d%d&Z0dYe$ee$ej%f eee$ej%f  ee$ d'd(d)Z1ee$ej%f ee$ej%f ee$ dd*d+d,Z2ej3ej4d-Z5ee$e&f e6d.< ee$ej%f ee$ej%f ee$ dd*d/d0Z7e2e7d1Z8ee$eee$ej%f ee$ej%f ee$ gdf f e6d2< e j9ej9ej9d3Z:ee$ed4ef f e6d5< d6d6d7d8Z;ee$eee$ ee$ f f e6d9< ee$ej%f ee$ee$ ee$ f d:d;d<Z<dZee$ej%f eee$ej%f  e)ej%d=d>d?Z=d[ee$ej%f eee$ej%f  e)ee$ej%f d=d@dAZ>d\e$ee$ej%f eee$ej%f  eee$ej%f  ee$ e)ddBdCdDZ?ee$dEdFdGZ@edHe$eAZBd]eBee$ eeeB  ee$ eBdIdJdKZCd^ee$ej%f e&ejDdLdMdNZEejFejFdOdPdQZGdS )_    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\}t|dF}t|jd.}|| }r`|	| |
t| q8W 5 Q R X W 5 Q R X W 5 Q R X d S )N
User-Agentheaderswb)total)urllibrequesturlopenRequest
USER_AGENTopenr   lengthreadwriteupdatelen)r   r   r   responsefhZpbarchunk r)   L/var/www/html/venv/lib/python3.8/site-packages/torchvision/datasets/utils.py_urlretrieve   s
    
r+      )fpathr   r   c              	   C   sX   t jdkrtjdd}nt }t| d }|| }rF|| q,W 5 Q R X | S )N)   	   F)Zusedforsecurityrb)sysversion_infohashlibmd5r    r"   r$   	hexdigest)r-   r   r4   fr(   r)   r)   r*   calculate_md5#   s    
r7   )r-   r4   kwargsr   c                 K   s   |t | f|kS N)r7   )r-   r4   r8   r)   r)   r*   	check_md51   s    r:   )r-   r4   r   c                 C   s&   t j| sdS |d krdS t| |S )NFT)ospathisfiler:   )r-   r4   r)   r)   r*   check_integrity5   s
    r>   r.   )r   max_hopsr   c                 C   s   | }dt d}t|d D ]V}tjtjj| |d4}|j| ksL|jd kr`| W  5 Q R    S |j} W 5 Q R X qtd| d| d|  dd S )	NHEAD)ZMethodr      r   zRequest to z
 exceeded z( redirects. The last redirect points to .)r   ranger   r   r   r   r   RecursionError)r   r?   Zinitial_urlr   _r&   r)   r)   r*   _get_redirect_url=   s    
rF   )r   r   c                 C   sB   t | }td|jd krd S td|j}|d kr8d S |dS )Nz(drive|docs)[.]google[.]comz/file/d/(?P<id>[^/]*)id)r   rematchnetlocr<   group)r   partsrI   r)   r)   r*   _get_google_drive_file_idM   s    rM   )r   rootr   r4   max_redirect_hopsr   c              
   C   s>  t j|}|st j| }t t j||}t j|dd t||rXtd|  dS t	 rjt
||  nt| |d} t| }|dk	rt||||S z"td|  d |  t| | W nn tjjtfk
r$ } zF| dd d	kr| d
d} td|  d |  t| | n|W 5 d}~X Y nX t||s:t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_okz$Using downloaded and verified file: N)r?   zDownloading  to    httpszhttps:zhttp:z;Failed download. Trying https -> http instead. Downloading File not found or corrupted.)r;   r<   
expanduserbasenamefspathjoinmakedirsr>   printr   r   rF   rM   download_file_from_google_driver+   r   errorURLErrorOSErrorreplaceRuntimeError)r   rN   r   r4   rO   r-   file_ider)   r)   r*   download_urlZ   s2    
rd   F)rN   prefixr   c                    sB   t j   fddt  D }|dk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;   r<   isdirrY   .0prN   r)   r*   
<listcomp>   s      zlist_dir.<locals>.<listcomp>Tc                    s   g | ]}t j |qS r)   r;   r<   rY   rh   drj   r)   r*   rk      s     r;   r<   rV   listdir)rN   re   directoriesr)   rj   r*   list_dir   s
    rr   )rN   suffixre   r   c                    sD   t j   fddt  D }|dk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;   r<   r=   rY   endswithrg   rN   rs   r)   r*   rk      s      
 zlist_files.<locals>.<listcomp>Tc                    s   g | ]}t j |qS r)   rl   rm   rj   r)   r*   rk      s     ro   )rN   rs   re   filesr)   ru   r*   
list_files   s
    
rw   )rb   rN   r   r4   c                 C   s   zddl }W n tk
r(   tdY nX tj|}|s>| }ttj||}tj|dd t	||rt
d|rvdnd d	|  dS |j| |d
td t	||st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'.TrP   zUsing downloaded zand verified  zfile: F)rG   outputquiet
user_agentrU   )gdownModuleNotFoundErrorra   r;   r<   rV   rX   rY   rZ   r>   r[   downloadr   )rb   rN   r   r4   r|   r-   r)   r)   r*   r\      s"    


r\   )	from_pathto_pathcompressionr   c              	   C   s<   t | |rd|dd   nd}|| W 5 Q R X d S )Nzr:rA   r)tarfiler    
extractall)r   r   r   tarr)   r)   r*   _extract_tar   s    $r   ).bz2.xz_ZIP_COMPRESSION_MAPc              	   C   s8   t j| d|rt| nt jd}|| W 5 Q R X 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)filer   c                 C   s   t | j}|s td|  d|d }|tkr>|ft| S |tkrP||dfS |tkrt|dkr|d }|tkr|| ||fS |d|fS tt	tt	tB t	tB }td| d| d	dS )
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.NrA   z&Unknown compression or archive type: 'z'.
Known suffixes are: 'z'.)
pathlibPathsuffixesra   r   r   r   r%   sortedset)r   r   rs   Zsuffix2Zvalid_suffixesr)   r)   r*   _detect_file_type   s$    


r   )r   r   remove_finishedr   c           	   
   C   s   t | \}}}|s"td| d|dkrNtt| ||dk	rF|nd}t| }|| d*}t|d}|	|
  W 5 Q R X W 5 Q R X |rt|  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 rB   Nrx   r0   r   )r   ra   r   r   r;   rX   r`   r   r    r#   r"   remove)	r   r   r   rs   archive_typer   Zcompressed_file_openerZrfhZwfhr)   r)   r*   _decompress)  s    $"
r   c           	   	      s   t jttt jf d fdd}|dkr4tj }t \}}}|svt tj	|tj
 |d|d}||S t| }| || |rt  |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 d S r9   )
isinstancestrr;   rX   )r   r   r)   r*   path_or_stra  s    

z$extract_archive.<locals>.path_or_strNrx   )r   )r   r   r   r   r;   r<   dirnamer   r   rY   rW   r`   r   r   )	r   r   r   r   rs   r   r   r   Z	extractorr)   r   r*   extract_archiveM  s      
r   )r   download_rootextract_rootr   r4   r   r   c                 C   sh   t j|}|d kr|}|s(t j| }t| ||| t j||}td| d|  t||| d S )NzExtracting rR   )r;   r<   rV   rW   rd   rY   r[   r   )r   r   r   r   r4   r   archiver)   r)   r*   download_and_extract_archive}  s    r   )iterabler   c                 C   s   dd dd | D  d S )N'z', 'c                 S   s   g | ]}t |qS r)   )r   )rh   itemr)   r)   r*   rk     s     z#iterable_to_str.<locals>.<listcomp>)rY   )r   r)   r)   r*   iterable_to_str  s    r   T)valueargvalid_values
custom_msgr   c                 C   s|   t | ts6|d krd}nd}|jt| |d}t||d krB| S | |krx|d k	rX|}n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_channelsr   c              	   C   s   t | d}|  }|dkr(tdtd| }|sDtddd | D \}}t|  }|dk r~d	}| }nd
}t	j
||d d}	W 5 Q R X |dkrd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.
    r0   )   PFs   PfzInvalid PFM files   ^(\d+)\s(\d+)\s$zMalformed PFM header.c                 s   s   | ]}t |V  qd S r9   )int)rh   dimr)   r)   r*   	<genexpr>  s     z_read_pfm.<locals>.<genexpr>r   <>r6   )dtyper   r.   rA   r   )ZaxisN)r    readlinerstripr   rH   rI   	ExceptiongroupsfloatnpfromfileZreshapeZ	transposeflipZastypeZfloat32)r   r   r6   headerZ	dim_matchwhscaleZendiandataZpfm_channelsr)   r)   r*   	_read_pfm  s&    	r   )tr   c                 C   sD   |   tjj| j|  f dj| jd d d | jS )Nr   )r   )
contiguousviewtorchZuint8shapeZelement_sizer   r   )r   r)   r)   r*   _flip_byte_order  s    Br   )r   )r,   )N)r.   )NNr.   )F)F)NN)NF)NF)NNNF)NNN)r   )Hbz2gzipr3   lzmar;   os.pathr   rH   r1   r   r   urllib.errorurllib.requestr   typingr   r   r   r   r   r   r   r	   r
   r   urllib.parser   numpyr   r   Ztorch.utils.model_zoor   Z_internally_replaced_utilsr   r   r   r   r   r   r+   r7   boolr:   r>   rF   rM   rd   rr   rw   r\   r   	ZIP_BZIP2ZIP_LZMAr   __annotations__r   r   r    r   r   r   r   r   r   r   bytesr   r   Zndarrayr   ZTensorr   r)   r)   r)   r*   <module>   s    0 "   8"$  '    
<&,-  &  3       
 $