U
    ­Ê¹j¤G  ã                	   @   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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!Z!d dl"m#Z# ddl$m%Z%m&Z& dZ'dXee( e)ee* ddœd	d
„Z+dYe)e)e*ddœdd„Z,dZe)e*e)dœdd„Z-e)e)ee.dœdd„Z/d[e)ee) e.dœdd„Z0d\e)e*e)dœdd„Z1e)ee) dœdd„Z2d]e)e)ee) ee) e*dd œd!d"„Z3d^e)e.ee) d$œd%d&„Z4d_e)e)e.ee) d'œd(d)„Z5d`e*ee(ee( f d*œd+d,„Z6dae)e)ee) ee) d-œd.d/„Z7e)e)ee) dd0œd1d2„Z8ej9ej:d3œZ;ee)e*f e<d4< e)e)ee) dd0œd5d6„Z=e8e=d7œZ>ee)ee)e)ee) gdf f e<d8< e j?ej?ej?d9œZ@ee)ed:ef f e<d;< d<d<d=d>œZAee)eee) ee) f f e<d?< e)ee)ee) ee) f d@œdAdB„ZBdbe)ee) e.e)dCœdDdE„ZCdce)ee) e.e)dCœdFdG„ZDdde)e)ee) ee) ee) e.ddHœdIdJ„ZEee)dKœdLdM„ZFedNe)e(ƒZGdeeGee) eeeG  ee) eGdOœdPdQ„ZHdfe)e*ejIdRœdSdT„ZJe!jKe!jKdUœdVdW„ZLdS )gé    N)
ÚAnyÚCallableÚDictÚIOÚIterableÚIteratorÚListÚOptionalÚTupleÚTypeVar)Úurlparse)Útqdmé   )Ú#_download_file_from_remote_locationÚ_is_remote_location_availablezpytorch/vision)ÚcontentÚdestinationÚlengthÚreturnc              
   C   sX   t |dƒ�D}t|d��.}| D ]"}|s&q| |¡ | t|ƒ¡ qW 5 Q R X W 5 Q R X d S )NÚwb)Útotal)Úopenr   ÚwriteÚupdateÚlen)r   r   r   ÚfhZpbarÚchunk© r   úY/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torchvision/datasets/utils.pyÚ_save_response_content   s    
r   é €  )ÚurlÚfilenameÚ
chunk_sizer   c              	      sL   t j t jj| dtid�¡�&‰tt‡ ‡fdd„dƒ|ˆjd� W 5 Q R X d S )Nú
User-Agent©Úheadersc                      s
   ˆ  ˆ ¡S ©N)Úreadr   ©r#   Úresponser   r   Ú<lambda>0   ó    z_urlretrieve.<locals>.<lambda>r,   )r   )ÚurllibÚrequestÚurlopenÚRequestÚ
USER_AGENTr   Úiterr   )r!   r"   r#   r   r)   r   Ú_urlretrieve.   s    r3   é   )Ú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)r5   r#   r<   Úfr   r   r   r   Úcalculate_md53   s    
r?   )r5   r<   Úkwargsr   c                 K   s   |t | f|ŽkS r'   )r?   )r5   r<   r@   r   r   r   Ú	check_md5A   s    rA   )r5   r<   r   c                 C   s&   t j | ¡sdS |d krdS t| |ƒS )NFT)ÚosÚpathÚisfilerA   )r5   r<   r   r   r   Úcheck_integrityE   s
    rE   r6   )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 Ú.)r1   Úranger-   r.   r/   r0   r!   ÚRecursionError)r!   rF   Zinitial_urlr&   Ú_r*   r   r   r   Ú_get_redirect_urlM   s    
ÿrM   )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ÚnetlocrC   Úgroup)r!   ÚpartsrP   r   r   r   Ú_get_google_drive_file_id]   s    rT   )r!   Úrootr"   r<   Úmax_redirect_hopsr   c              
   C   s8  t j |¡}|st j | ¡}t j ||¡}t j|dd� t||ƒrRtd| ƒ dS tƒ rdt	|| ƒ n¼t
| |d�} t| ƒ}|dk	rŽt||||ƒ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||ƒ�s4t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)rF   zDownloading ú to é   Úhttpszhttps:zhttp:z;Failed download. Trying https -> http instead. Downloading zFile not found or corrupted.)rB   rC   Ú
expanduserÚbasenameÚjoinÚmakedirsrE   Úprintr   r   rM   rT   Údownload_file_from_google_driver3   r-   ÚerrorÚURLErrorÚOSErrorÚreplaceÚRuntimeError)r!   rU   r"   r<   rV   r5   Úfile_idÚer   r   r   Údownload_urlj   s2    
ri   F)rU   Ú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   )rB   rC   Úisdirr^   ©Ú.0Úp©rU   r   r   Ú
<listcomp>§   s      zlist_dir.<locals>.<listcomp>Tc                    s   g | ]}t j ˆ |¡‘qS r   ©rB   rC   r^   ©rm   Údro   r   r   rp   ©   s     ©rB   rC   r\   Úlistdir)rU   rj   Údirectoriesr   ro   r   Úlist_dirž   s
    rw   )rU   Úsuffixrj   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   )rB   rC   rD   r^   Úendswithrl   ©rU   rx   r   r   rp   ¸   s      
 zlist_files.<locals>.<listcomp>Tc                    s   g | ]}t j ˆ |¡‘qS r   rq   rr   ro   r   r   rp   º   s     rt   )rU   rx   rj   Úfilesr   rz   r   Ú
list_files­   s
    
r|   )r#   r   c                 C   st   |   |¡}d }|st|ƒ}qt |g|¡}z(t d| ¡ ¡}|d k	rL|d nd }W n tk
rj   d }Y nX ||fS )Nz3<title>Google Drive - (?P<api_response>.+?)</title>Úapi_response)Úiter_contentÚnextÚ	itertoolsÚchainrO   ÚsearchÚdecodeÚUnicodeDecodeError)r*   r#   r   Zfirst_chunkrP   r}   r   r   r   Ú_extract_gdrive_api_response¾   s    


r…   )rg   rU   r"   r<   c              
   C   s¨  t j |¡}|s| }t j ||¡}t j|dd� t||ƒrZtd|rFdnd› d|› �ƒ dS d}t| d	d
�}t 	¡ �¨}|j
||dd�}|j ¡ D ]\}	}
|	 d¡rŽ|
} qÆqŽt|ƒ\}}|dkrÂdnd}|dk	rò|j
|t||d�dd�}t|ƒ\}}|dk�rtd|› d�ƒ‚t||ƒ W 5 Q R X t  |¡jdk �r‚t t¡�@ t|ƒ�,}| ¡ }t d|¡�rnt d|› �¡ W 5 Q R X W 5 Q R X |�r¤t||ƒ�s¤td|› 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
    TrW   zUsing downloaded zand verified Ú zfile: Nzhttps://drive.google.com/ucÚdownload)rN   Zexport)ÚparamsÚstreamZdownload_warningzVirus scan warningÚt)ZconfirmzQuota exceededzThe daily quota of the file z} is exceeded and it can't be downloaded. This is a limitation of Google Drive and can only be overcome by trying again later.i (  z5</?\s*[a-z-][^>]*\s*>|(&(?:[\w\d]+|#\d+|#x[a-f\d]+);)zöWe detected some HTML elements in the downloaded file. This most likely means that the download triggered an unhandled API response by GDrive. Please report this to torchvision at https://github.com/pytorch/vision/issues including the response:

z&The MD5 checksum of the download file z­ does not match the one on record.Please delete the file and try again. If the issue persists, please report this to torchvision at https://github.com/pytorch/vision/issues.)rB   rC   r\   r^   r_   rE   r`   ÚdictÚrequestsÚSessionÚgetÚcookiesÚitemsÚ
startswithr…   rf   r   ÚstatÚst_sizeÚ
contextlibÚsuppressr„   r   r(   rO   r‚   ÚwarningsÚwarnrA   )rg   rU   r"   r<   r5   r!   rˆ   Úsessionr*   ÚkeyÚvalueÚtokenr}   r   r   Útextr   r   r   ra   Î   sJ    




ÿÿ
ÿra   )Ú	from_pathÚto_pathÚcompressionr   c              	   C   s<   t  | |rd|dd … › �nd¡�}| |¡ W 5 Q R X d S )Nzr:rH   Ú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rŒt|ƒ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.éÿÿÿÿNrH   éþÿÿÿz&Unknown compression or archive type: 'z'.
Known suffixes are: 'z'.)
ÚpathlibÚPathÚsuffixesrf   r±   r®   r°   r   ÚsortedÚset)r²   r·   rx   Zsuffix2Zvalid_suffixesr   r   r   Ú_detect_file_type5  s$    
ÿ

rº   )r�   rž   Úremove_finishedr   c           	   
   C   s–   t | ƒ\}}}|s"td|› d�ƒ‚|dkrB|  ||dk	r<|nd¡}t| }|| dƒ�*}t|dƒ�}| | ¡ ¡ W 5 Q R X W 5 Q R X |r’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 rI   Nr†   r8   r   )	rº   rf   re   r°   r   r   r(   rB   Úremove)	r�   rž   r»   rx   Úarchive_typerŸ   Zcompressed_file_openerZrfhZwfhr   r   r   Ú_decompress`  s    "
r¾   c              	   C   st   |dkrt j | ¡}t| ƒ\}}}|sNt| t j |t j | ¡ |d¡¡|d�S t| }|| ||ƒ |rpt  	| ¡ |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.
    Nr†   )r»   )
rB   rC   Údirnamerº   r¾   r^   r]   re   r®   r¼   )r�   rž   r»   rx   r½   rŸ   Z	extractorr   r   r   Úextract_archive€  s    ý
rÀ   )r!   Údownload_rootÚextract_rootr"   r<   r»   r   c                 C   sh   t j |¡}|d kr|}|s(t j | ¡}t| |||ƒ t j ||¡}td|› d|› �ƒ t|||ƒ d S )NzExtracting rY   )rB   rC   r\   r]   ri   r^   r`   rÀ   )r!   rÁ   rÂ   r"   r<   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   )Ústr)rm   Úitemr   r   r   rp   º  s     z#iterable_to_str.<locals>.<listcomp>)r^   )rÅ   r   r   r   Úiterable_to_str¹  s    rÉ   ÚT)rš   Ú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Ì   )Ú
isinstancerÇ   Ú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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.
    r8   )ó   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>   )ÚdtyperÖ   r6   rH   r   )ZaxisN)r   ÚreadlineÚrstriprÑ   rO   rP   Ú	ExceptionÚgroupsÚfloatÚnpÚfromfileZreshapeZ	transposeÚflipZastypeZfloat32)rÔ   rÕ   r>   ÚheaderZ	dim_matchÚwÚhÚscaleZendianÚdataZpfm_channelsr   r   r   Ú	_read_pfmÜ  s&    	rê   )rŠ   r   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    Bÿrï   )N)r    )r4   )N)r6   )NNr6   )F)F)r    )NN)NF)NF)NNNF)NNN)r   )MÚbz2r”   Úgzipr;   r€   ÚlzmarB   Úos.pathrµ   rO   r9   r¡   r-   Úurllib.errorÚurllib.requestr–   r¨   Útypingr   r   r   r   r   r   r   r	   r
   r   Úurllib.parser   Únumpyrâ   rŒ   rí   Ztorch.utils.model_zoor   Z_internally_replaced_utilsr   r   r1   ÚbytesrÇ   r×   r   r3   r?   ÚboolrA   rE   rM   rT   ri   rw   r|   r…   ra   r¤   Ú	ZIP_BZIP2ÚZIP_LZMAr§   Ú__annotations__r¬   r®   r   r°   r±   rº   r¾   rÀ   rÄ   rÉ   rÊ   rÓ   Zndarrayrê   ZTensorrï   r   r   r   r   Ú<module>   sÆ    0 ýü     ÿ    þ4Eþþ(ýý&"+ '    úù   ü
û$