o
    )iG                     @   sn  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'	dcdee( d	e)d
ee* ddfddZ+ddde)de)de*ddfddZ,dede)de*de)fddZ-de)de)dede.fddZ/dcde)dee) de.fddZ0dfde)de*de)fd d!Z1de)dee) fd"d#Z2	dgde)d$e)dee) dee) d%e*ddfd&d'Z3dhd$e)d)e.dee) fd*d+Z4dhd$e)d,e)d)e.dee) fd-d.Z5ddde*dee(ee( f fd/d0Z6did1e)d$e)dee) dee) fd2d3Z7d4e)d5e)d6ee) ddfd7d8Z8ej9ej:d9Z;ee)e*f e<d:< d4e)d5e)d6ee) ddfd;d<Z=e8e=d=Z>ee)ee)e)ee) gdf f e<d>< e j?ej?ej?d?Z@ee)ed@ef f e<dA< dBdBdCdDZAee)eee) ee) f f e<dE< dFe)dee)ee) ee) f fdGdHZBdjd4e)d5ee) dIe.de)fdJdKZCdjd4e)d5ee) dIe.de)fdLdMZD				(dkde)dNe)dOee) dee) dee) dIe.ddfdPdQZEdRede)fdSdTZFedUe)e(ZG			dldVeGdWee) dXeeeG  dYee) deGf
dZd[ZHdmd\e)d]e*dejIfd^d_ZJd`e!jKde!jKfdadbZLdS )n    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:}t|d}| D ]}|sq|| |t| qW d    n1 s*w   Y  W d    d S W d    d S 1 sBw   Y  d S )Nwb)total)openr   writeupdatelen)r   r   r   fhZpbarchunk r   i/var/www/html/eduruby.in/lip-sync/lip-sync-env/lib/python3.10/site-packages/torchvision/datasets/utils.py_save_response_content   s   
Pr      urlfilename
chunk_sizec                    sb   t jt jj| dtidtt fddd|jd W d    d S 1 s*w   Y  d S )N
User-Agentheadersc                      s
     S N)readr   r#   responser   r   <lambda>0   s   
 z_urlretrieve.<locals>.<lambda>    )r   )urllibrequesturlopenRequest
USER_AGENTr   iterr   )r!   r"   r#   r   r)   r   _urlretrieve.   s   ""r3      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)r5   r#   r=   fr   r   r   r   calculate_md53   s   



r@   r=   kwargsc                 K   s   |t | fi |kS r'   )r@   )r5   r=   rA   r   r   r   	check_md5A   s   rB   c                 C   s&   t j| sdS |d u rdS t| |S )NFT)ospathisfilerB   )r5   r=   r   r   r   check_integrityE   s
   
rF   r6   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)ZMethodr$      r%   zRequest to z
 exceeded z( redirects. The last redirect points to .)r1   ranger-   r.   r/   r0   r!   RecursionError)r!   rG   Zinitial_urlr&   _r*   r   r   r   _get_redirect_urlM   s   
rN   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netlocrD   group)r!   partsrQ   r   r   r   _get_google_drive_file_id]   s   
rU   rootmax_redirect_hopsc              
   C   s4  t j|}|st j| }t j||}t j|dd t||r)td|  dS t r2t	||  n]t
| |d} t| }|durGt||||S ztd|  d |  t| | W n6 tjjtfy } z&| dd d	kr| d
d} t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_okz$Using downloaded and verified file: N)rG   zDownloading  to    httpszhttps:zhttp:z;Failed download. Trying https -> http instead. Downloading zFile not found or corrupted.)rC   rD   
expanduserbasenamejoinmakedirsrF   printr   r   rN   rU   download_file_from_google_driver3   r-   errorURLErrorOSErrorreplaceRuntimeError)r!   rV   r"   r=   rW   r5   file_ider   r   r   download_urlj   s:   

	rj   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   )rC   rD   isdirr_   .0prV   r   r   
<listcomp>   s   & zlist_dir.<locals>.<listcomp>Tc                       g | ]	}t j |qS r   rC   rD   r_   rn   drp   r   r   rq          rC   rD   r]   listdir)rV   rk   directoriesr   rp   r   list_dir   s
   rz   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   )rC   rD   rE   r_   endswithrm   rV   r{   r   r   rq      s   0 zlist_files.<locals>.<listcomp>Tc                    rr   r   rs   rt   rp   r   r   rq      rv   rw   )rV   r{   rk   filesr   r}   r   
list_files   s
   
r   c                 C   sx   |  |}d }|st|}|r	t|g|}ztd| }|d ur'|d nd }W ||fS  ty;   d }Y ||fS w )Nz3<title>Google Drive - (?P<api_response>.+?)</title>api_response)iter_contentnext	itertoolschainrP   searchdecodeUnicodeDecodeError)r*   r#   r   Zfirst_chunkrQ   r   r   r   r   _extract_gdrive_api_response   s   
r   rh   c              	   C   s  t j|}|s
| }t j||}t j|dd t||r-td|r#dnd d|  dS d}t| d	d
}t	 X}|j
||dd}|j D ]\}	}
|	drT|
} nqGt|\}}|dkradnd}|dury|j
|t||ddd}t|\}}|dkrtd| dt|| W d   n1 sw   Y  t |jdk rtt. t|}| }td|rtd|  W d   n1 sw   Y  W d   n1 sw   Y  |rt||std| ddS 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
    TrX   zUsing downloaded zand verified  zfile: Nzhttps://drive.google.com/ucdownload)rO   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]+);)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.)rC   rD   r]   r_   r`   rF   ra   dictrequestsSessiongetcookiesitems
startswithr   rg   r   statst_size
contextlibsuppressr   r   r(   rP   r   warningswarnrB   )rh   rV   r"   r=   r5   r!   r   sessionr*   keyvaluetokenr   r   r   textr   r   r   rb      s\   



 
rb   	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:rI   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.NrI   z&Unknown compression or archive type: 'z'.
Known suffixes are: 'z'.)
pathlibPathsuffixesrg   r   r   r   r   sortedset)r   r   r{   Zsuffix2Zvalid_suffixesr   r   r   _detect_file_type5  s$   


r   remove_finishedc           	   	   C   s   t | \}}}|std| d|du r!| ||dur|nd}t| }|| d$}t|d}||  W d   n1 sBw   Y  W d   n1 sQw   Y  |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 rJ   Nr   r9   r   )	r   rg   rf   r   r   r   r(   rC   remove)	r   r   r   r{   archive_typer   Zcompressed_file_openerZrfhZwfhr   r   r   _decompress`  s    
r   c              	   C   st   |du r
t j| }t| \}}}|s't| t j|t j| |d|dS t| }|| || |r8t 	|  |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   )
rC   rD   dirnamer   r   r_   r^   rf   r   r   )r   r   r   r{   r   r   Z	extractorr   r   r   extract_archive  s   
r   download_rootextract_rootc                 C   sh   t j|}|d u r|}|st j| }t| ||| t j||}td| d|  t||| d S )NzExtracting rZ   )rC   rD   r]   r^   rj   r_   ra   r   )r!   r   r   r"   r=   r   archiver   r   r   download_and_extract_archive  s   r   iterablec                 C   s   dd dd | D  d S )N'z', 'c                 S   s   g | ]}t |qS r   )str)rn   itemr   r   r   rq     s    z#iterable_to_str.<locals>.<listcomp>)r_   )r   r   r   r   iterable_to_str  s   r   Tr   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   )
isinstancer   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.
    r9   )   PFs   PfzInvalid PFM files   ^(\d+)\s(\d+)\s$zMalformed PFM header.c                 s   s    | ]}t |V  qd S r'   )int)rn   dimr   r   r   	<genexpr>  s    z_read_pfm.<locals>.<genexpr>r   <>r?   )dtypeNr   r6   rI   r   )Zaxis)r   readlinerstripr   rP   rQ   	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   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   Lr   r'   )r    )r4   )r6   )NNr6   )F)NN)NF)NNNF)NNN)r   )Mbz2r   gzipr<   r   lzmarC   Zos.pathr   rP   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   r1   bytesr   r   r   r3   r@   boolrB   rF   rN   rU   rj   rz   r   r   rb   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(&$ +  '


$