a
    dG                  	   @   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   s   t |db}t|d8}| D ]"}|s&q|| |t| qW d    n1 sT0    Y  W d    n1 sr0    Y  d S )Nwb)total)openr   writeupdatelen)r   r   r   fhZpbarchunk r   c/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchvision/datasets/utils.py_save_response_content   s    
r      )urlfilename
chunk_sizer   c                    s`   t jt jj| dtid0tt fddd|jd W d    n1 sR0    Y  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    r4      )fpathr#   r   c                    sv   t jdkrtjdd}nt }t| d4t fdddD ]}|| q@W d    n1 sd0    Y  | S )N)   	   F)usedforsecurityrbc                      s
     S r'   r(   r   r#   fr   r   r,   <   r-   zcalculate_md5.<locals>.<lambda>r-   )sysversion_infohashlibmd5r   r3   r   	hexdigest)r6   r#   r@   r   r   r;   r   calculate_md53   s    
*rB   )r6   r@   kwargsr   c                 K   s   |t | fi |kS r'   )rB   )r6   r@   rC   r   r   r   	check_md5A   s    rD   )r6   r@   r   c                 C   s&   t j| sdS |d u rdS t| |S )NFT)ospathisfilerD   )r6   r@   r   r   r   check_integrityE   s
    rH   r7   )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 .)r2   ranger.   r/   r0   r1   r!   RecursionError)r!   rI   Zinitial_urlr&   _r+   r   r   r   _get_redirect_urlM   s    
&rP   )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netlocrF   group)r!   partsrS   r   r   r   _get_google_drive_file_id]   s    rW   )r!   rootr"   r@   max_redirect_hopsr   c              
   C   s:  t j|}|st j| }t j||}t j|dd t||rRtd|  dS t rdt	||  nt
| |d} t| }|durt||||S z"td|  d |  t| | W np tjjtfy  } zN| dd d	kr| d
d} td|  d |  t| | n|W Y d}~n
d}~0 0 t||s6t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)rI   zDownloading  to    httpszhttps:zhttp:z;Failed download. Trying https -> http instead. Downloading zFile not found or corrupted.)rE   rF   
expanduserbasenamejoinmakedirsrH   printr   r   rP   rW   download_file_from_google_driver4   r.   errorURLErrorOSErrorreplaceRuntimeError)r!   rX   r"   r@   rY   r6   file_ider   r   r   download_urlj   s2    
rl   F)rX   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   )rE   rF   isdirra   .0prX   r   r   
<listcomp>   r-   zlist_dir.<locals>.<listcomp>Tc                    s   g | ]}t j |qS r   rE   rF   ra   rp   drr   r   r   rs      r-   rE   rF   r_   listdir)rX   rm   directoriesr   rr   r   list_dir   s
    rz   )rX   suffixrm   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   )rE   rF   rG   ra   endswithro   rX   r{   r   r   rs      r-   zlist_files.<locals>.<listcomp>Tc                    s   g | ]}t j |qS r   rt   ru   rr   r   r   rs      r-   rw   )rX   r{   rm   filesr   r}   r   
list_files   s
    
r   )r#   r   c                 C   sr   |  |}d }|st|}qt|g|}z(td| }|d urL|d nd }W n tyh   d }Y n0 ||fS )Nz3<title>Google Drive - (?P<api_response>.+?)</title>api_response)iter_contentnext	itertoolschainrR   searchdecodeUnicodeDecodeError)r+   r#   r   Zfirst_chunkrS   r   r   r   r   _extract_gdrive_api_response   s    


r   )rj   rX   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|
} qqt|\}}|dkrdnd}|dur|j
|t||ddd}t|\}}|dkrtd| dt|| W d   n1 s,0    Y  t |jdk rtt` t|6}| }td|rtd|  W d   n1 s0    Y  W d   n1 s0    Y  |rt||st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
    TrZ   zUsing downloaded zand verified  zfile: Nzhttps://drive.google.com/ucdownload)rQ   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]+);)zWe 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.)rE   rF   r_   ra   rb   rH   rc   dictrequestsSessiongetcookiesitems
startswithr   ri   r   statst_size
contextlibsuppressr   r   r)   rR   r   warningswarnrD   )rj   rX   r"   r@   r6   r!   r   sessionr+   keyvaluetokenr   r   r   textr   r   r   rd      sN    




*D
rd   )	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:rK   r)tarfiler   
extractall)r   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   )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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.NrK   z&Unknown compression or archive type: 'z'.
Known suffixes are: 'z'.)
pathlibPathsuffixesri   r   r   r   r   sortedset)r   r   r{   Zsuffix2Zvalid_suffixesr   r   r   _detect_file_type5  s$    


r   )r   r   remove_finishedr   c           	   	   C   s   t | \}}}|s"td| d|du rB| ||dur<|nd}t| }|| dH}t|d}||  W d   n1 s0    Y  W d   n1 s0    Y  |rt|  |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 rL   Nr   r:   r   )	r   ri   rh   r   r   r   r)   rE   remove)	r   r   r   r{   archive_typer   Zcompressed_file_openerZrfhZwfhr   r   r   _decompress`  s    J
r   c              	   C   st   |du 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   )
rE   rF   dirnamer   r   ra   r`   rh   r   r   )r   r   r   r{   r   r   Z	extractorr   r   r   extract_archive  s    
r   )r!   download_rootextract_rootr"   r@   r   r   c                 C   sh   t j|}|d u r|}|s(t j| }t| ||| t j||}td| d|  t||| d S )NzExtracting r\   )rE   rF   r_   r`   rl   ra   rc   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)rp   itemr   r   r   rs     r-   z#iterable_to_str.<locals>.<listcomp>)ra   )r   r   r   r   iterable_to_str  s    r   T)r   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   )
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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 r'   )int)rp   Zdimr   r   r   	<genexpr>  r-   z_read_pfm.<locals>.<genexpr>r   <>r<   )dtypeNr   r7   rK   r   )Zaxis)r   readlinerstripr   rR   rS   	ExceptiongroupsfloatnpfromfileZreshapeZ	transposeflipZastypefloat32)r   r   r<   headerZ	dim_matchwhZscaleZendiandataZpfm_channelsr   r   r   	_read_pfm  s&    	0r   )r   r   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   )N)r    )r5   )N)r7   )NNr7   )F)F)r    )NN)NF)NF)NNNF)NNN)r   )Mbz2r   gzipr?   r   lzmarE   os.pathr   rR   r=   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   r2   bytesr   r   r   r4   rB   boolrD   rH   rP   rW   rl   rz   r   r   rd   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(&"+ '       
$