a
    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mZ d dl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 dSe!ee!ej"f e#dd
ddZ$dTee!ej"f e#e!dddZ%ee!ej"f e!ee&dddZ'dUee!ej"f ee! e&dddZ(dVe!e#e!dddZ)e!ee! dddZ*dWe!ee!ej"f eee!ej"f  ee! e#dddd Z+dXee!ej"f e&e,e! d"d#d$Z-dYee!ej"f e!e&e,e! d%d&d'Z.dZe!ee!ej"f eee!ej"f  ee! d(d)d*Z/ee!ej"f ee!ej"f ee! dd+d,d-Z0ej1ej2d.Z3e4e!e#f e5d/< ee!ej"f ee!ej"f ee! dd+d0d1Z6e0e6d2Z7e4e!eee!ej"f ee!ej"f ee! gdf f e5d3< e j8ej8ej8d4Z9e4e!ed5ef f e5d6< d7d7d8d9Z:e4e!e;ee! ee! f f e5d:< ee!ej"f e;e!ee! ee! f d;d<d=Z<d[e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>dAdBZ>d]e!ee!ej"f eee!ej"f  eee!ej"f  ee! e&ddCdDdEZ?ee!dFdGdHZ@edIe!eAZBd^eBee! eeeB  ee! eBdJdKdLZCd_ee!ej"f e#ejDdMdNdOZEejFejFdPdQdRZGdS )`    N)Iterable)AnyCallableIOOptional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h}t|jddd8}|| }rd|	| |
t| q<W d    n1 sx0    Y  W d    n1 s0    Y  W d    n1 s0    Y  d S )N
User-AgentheaderswbBT)totalunitZ
unit_scale)urllibrequesturlopenRequest
USER_AGENTopenr
   lengthreadwriteupdatelen)r   r   r   responsefhZpbarchunk r(   H/var/www/auris/lib/python3.9/site-packages/torchvision/datasets/utils.py_urlretrieve   s
    
r*      )fpathr   r   c                 C   sX   t jdd}t| d*}|| }r2|| qW d    n1 sF0    Y  | S )NF)usedforsecurityrb)hashlibmd5r   r!   r#   	hexdigest)r,   r   r0   fr'   r(   r(   r)   calculate_md5#   s
    *r3   )r,   r0   kwargsr   c                 K   s   |t | fi |kS N)r3   )r,   r0   r4   r(   r(   r)   	check_md5.   s    r6   )r,   r0   r   c                 C   s&   t j| sdS |d u rdS t| |S )NFT)ospathisfiler6   )r,   r0   r(   r(   r)   check_integrity2   s
    r:      )r   max_hopsr   c              	   C   s   | }dt d}t|d D ]l}tjtjj| |d@}|j| ksL|jd u rb| W  d      S |j} W d    q1 s|0    Y  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    
&rC   )r   r   c                 C   sB   t | }td|jd u rd S td|j}|d u r8d S |dS )Nz(drive|docs)[.]google[.]comz/file/d/(?P<id>[^/]*)id)r	   rematchnetlocr8   group)r   partsrF   r(   r(   r)   _get_google_drive_file_idJ   s    rJ   )r   rootr   r0   max_redirect_hopsr   c              
   C   s  t j|}|st j| }t t j||}t j|dd t||rLdS t r^t	||  nt
| |d} t| }|durt||||S zt| | W nX tjjtfy } z8| dd dkr| dd} t| | n|W Y d}~n
d}~0 0 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_okN)r<      httpszhttps:zhttp:File not found or corrupted.)r7   r8   
expanduserbasenamefspathjoinmakedirsr:   r   r   rC   rJ   download_file_from_google_driver*   r   errorURLErrorOSErrorreplaceRuntimeError)r   rK   r   r0   rL   r,   file_ider(   r(   r)   download_urlW   s,    
r_   F)rK   prefixr   c                    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(   )r7   r8   isdirrU   .0prK   r(   r)   
<listcomp>       zlist_dir.<locals>.<listcomp>Tc                    s   g | ]}t j |qS r(   r7   r8   rU   rc   dre   r(   r)   rf      rg   r7   r8   rR   listdir)rK   r`   directoriesr(   re   r)   list_dir   s
    rn   )rK   suffixr`   r   c                    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(   )r7   r8   r9   rU   endswithrb   rK   ro   r(   r)   rf      rg   zlist_files.<locals>.<listcomp>Tc                    s   g | ]}t j |qS r(   rh   ri   re   r(   r)   rf      rg   rk   )rK   ro   r`   filesr(   rq   r)   
list_files   s
    
rs   )r]   rK   r   r0   c                 C   s   zddl }W n ty&   tdY n0 tj|}|s<| }ttj||}tj|dd t	||rld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'.TrM   F)rD   outputquiet
user_agentrQ   )gdownModuleNotFoundErrorr\   r7   r8   rR   rT   rU   rV   r:   downloadr   )r]   rK   r   r0   rw   r,   r(   r(   r)   rW      s     


rW   )	from_pathto_pathcompressionr   c                 C   sP   t | |rd|dd   nd}|| W d    n1 sB0    Y  d S )Nzr:r>   r)tarfiler   
extractall)rz   r{   r|   tarr(   r(   r)   _extract_tar   s    $r   ).bz2.xz_ZIP_COMPRESSION_MAPc                 C   sL   t j| d|rt| nt jd}|| W d    n1 s>0    Y  d S )Nr}   )r|   )zipfileZipFiler   
ZIP_STOREDr   )rz   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v r@|gt| R S |tv rR||dfS |tv rt|dkr|d }|tv 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.Nr>   z&Unknown compression or archive type: 'z'.
Known suffixes are: 'z'.)
pathlibPathsuffixesr\   r   r   r   r$   sortedset)r   r   ro   Zsuffix2Zvalid_suffixesr(   r(   r)   _detect_file_type   s$    


r   )rz   r{   remove_finishedr   c           	   	   C   s   t | \}}}|s"td| d|du rNtt| ||durF|nd}t| }|| dH}t|d}|	|
  W d   n1 s0    Y  W d   n1 s0    Y  |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 r?   N r.   r   )r   r\   r   r   r7   rT   r[   r   r   r"   r!   remove)	rz   r{   r   ro   archive_typer|   Zcompressed_file_openerZrfhZwfhr(   r(   r)   _decompress"  s    $J
r   c           	   	      s   t jttt jf d fdd}|du 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 r5   )
isinstancestrr7   rT   )r   rz   r(   r)   path_or_strZ  s    

z$extract_archive.<locals>.path_or_strNr   )r   )r   r   r   r   r7   r8   dirnamer   r   rU   rS   r[   r   r   )	rz   r{   r   r   ro   r   r|   r   Z	extractorr(   r   r)   extract_archiveF  s      
r   )r   download_rootextract_rootr   r0   r   r   c                 C   sT   t j|}|d u r|}|s(t j| }t| ||| t j||}t||| d S r5   )r7   r8   rR   rS   r_   rU   r   )r   r   r   r   r0   r   archiver(   r(   r)   download_and_extract_archivev  s    r   )iterabler   c                 C   s   dd dd | D  d S )N'z', 'c                 S   s   g | ]}t |qS r(   )r   )rc   itemr(   r(   r)   rf     rg   z#iterable_to_str.<locals>.<listcomp>)rU   )r   r(   r(   r)   iterable_to_str  s    r   T)valueargvalid_values
custom_msgr   c                 C   s|   t | ts6|d u rd}nd}|jt| |d}t||d u rB| S | |vrx|d u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vr(tdtd| }|sDtddd | D \}}t|  }|dk r~d	}| }nd
}t	j
||d d}	W d   n1 s0    Y  |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.
    r.   )   PFs   PfzInvalid PFM files   ^(\d+)\s(\d+)\s$zMalformed PFM header.c                 s   s   | ]}t |V  qd S r5   )int)rc   Zdimr(   r(   r)   	<genexpr>  rg   z_read_pfm.<locals>.<genexpr>r   <>r2   )dtypeNr   r;   r>   r   )Zaxis)r   readlinerstripr   rE   rF   	ExceptiongroupsfloatnpfromfileZreshapeZ	transposeflipZastypefloat32)r   r   r2   headerZ	dim_matchwhZscaleZendiandataZpfm_channelsr(   r(   r)   	_read_pfm  s&    	0r   )tr   c                 C   sN   |   tjjg | j|  R  djg | jd d dR  | jS )Nr   )
contiguousviewtorchZuint8shapeZelement_sizer   r   )r   r(   r(   r)   _flip_byte_order  s    Lr   )r   )r+   )N)r;   )NNr;   )F)F)NN)NF)NF)NNNF)NNN)r   )Hbz2gzipr/   lzmar7   os.pathr   rE   r~   r   urllib.errorurllib.requestr   collections.abcr   typingr   r   r   r   r   r   urllib.parser	   numpyr   r   Ztorch.utils.model_zoor
   Z_internally_replaced_utilsr   r   r   r   r   r   r*   r3   boolr6   r:   rC   rJ   r_   listrn   rs   rW   r   	ZIP_BZIP2ZIP_LZMAr   dict__annotations__r   r   r   r   r   tupler   r   r   r   r   bytesr   r   Zndarrayr   ZTensorr   r(   r(   r(   r)   <module>   s   
  "   5"$  &
<&,-  &  3       
 $