a
    âñh.  ã                
   @   s¼  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 d dlmZmZmZmZmZmZ d dlZd dlZd dlZd dlmZ d dlmZ e
eedœdd	„Zedd
œdd„Zd+eee eeedœdd„Z d,eeee ee eeeddœdd„Z!d-eeeedœdd„Z"d.eee eee dœdd„Z#d/eeeee f eeee dœdd„Z$G d d!„ d!eƒZ%d0eeed#œd$d%„Z&G d&d'„ d'ej'ƒZ(eeed(œd)d*„Z)dS )1é    N)ÚTextIOWrapper)ÚQueue)ÚAnyÚIterableÚListÚOptionalÚTupleÚUnion)ÚDataset)Útqdm)Úunicode_csv_dataÚkwargsÚreturnc                 k   sf   t j}zt |¡ W q:W q ty6   t|d ƒ}Y q0 qt |¡ tj| fi |¤ŽD ]
}|V  qVdS )aý  Since the standard csv library does not handle unicode in Python 2, we need a wrapper.
    Borrowed and slightly modified from the Python docs:
    https://docs.python.org/2/library/csv.html#csv-examples
    Args:
        unicode_csv_data (TextIOWrapper): unicode csv data (see example below)

    Examples:
        >>> from torchaudio.datasets.utils import unicode_csv_reader
        >>> import io
        >>> with io.open(data_path, encoding="utf8") as f:
        >>>     reader = unicode_csv_reader(f)
    é
   N)ÚsysÚmaxsizeÚcsvÚfield_size_limitÚOverflowErrorÚintÚreader)r   r   ZmaxIntÚline© r   úY/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchaudio/datasets/utils.pyÚunicode_csv_reader   s    

r   )Údirpathr   c              
   C   sH   zt  | ¡ W n4 tyB } z|jtjkr,n‚ W Y d}~n
d}~0 0 dS )z<
    Python2 support for os.makedirs(.., exist_ok=True)
    N)ÚosÚmakedirsÚOSErrorÚerrnoÚEEXIST)r   Úer   r   r   Úmakedir_exist_ok3   s    r"   é €  T)ÚurlÚ
start_byteÚ
block_sizeÚprogress_barr   c           
   	   c   sò   t jj| dd�}tt j |¡ ¡  dd¡ƒ}||kr8dS t j | ¡}|rXd |¡|jd< t j |¡�z}t	dd	d
|| d��F}d}| 
|¡}	|	s�q²|	V  |t|	ƒ7 }| t|	ƒ¡ q€W d  ƒ n1 sÆ0    Y  W d  ƒ n1 sä0    Y  dS )a<  Stream url by chunk

    Args:
        url (str): Url.
        start_byte (int, optional): Start streaming at that point (Default: ``None``).
        block_size (int, optional): Size of chunks to stream (Default: ``32 * 1024``).
        progress_bar (bool, optional): Display a progress bar (Default: ``True``).
    ÚHEAD©ÚmethodúContent-LengthéÿÿÿÿNz	bytes={}-ZRangeÚBTi   )ÚunitZ
unit_scaleZunit_divisorÚtotalÚdisabler   )ÚurllibÚrequestÚRequestr   ÚurlopenÚinfoÚgetÚformatÚheadersr   ÚreadÚlenÚupdate)
r$   r%   r&   r'   ÚreqZurl_sizeZupointerZpbarÚ	num_bytesÚchunkr   r   r   Ú
stream_url@   s,    û
r?   Úsha256F)r$   Údownload_folderÚfilenameÚ
hash_valueÚ	hash_typer'   Úresumer   c                 C   sš  t jj| dd�}t j |¡ ¡ }|p6| ¡ p6tj | ¡}tj 	||¡}	|rhtj 
|	¡rhd}
tj |	¡}n(|sˆtj 
|	¡rˆtd |	¡ƒ‚nd}
d}|rü|t| dd¡ƒkrüt|	d	ƒ�,}t|||ƒrÐW d  ƒ dS W d  ƒ n1 sä0    Y  td
 |	¡ƒ‚t|	|
ƒ�0}t| ||d�D ]}| |¡ �qW d  ƒ n1 �s>0    Y  t|	d	ƒ�2}|�rvt|||ƒ�svtd
 |	¡ƒ‚W d  ƒ n1 �sŒ0    Y  dS )a4  Download file to disk.

    Args:
        url (str): Url.
        download_folder (str): Folder to download file.
        filename (str, optional): Name of downloaded file. If None, it is inferred from the url (Default: ``None``).
        hash_value (str, optional): Hash for url (Default: ``None``).
        hash_type (str, optional): Hash type, among "sha256" and "md5" (Default: ``"sha256"``).
        progress_bar (bool, optional): Display a progress bar (Default: ``True``).
        resume (bool, optional): Enable resuming download (Default: ``False``).
    r(   r)   Úabz6{} already exists. Delete the file manually and retry.ÚwbNr+   r,   ÚrbzBThe hash of {} does not match. Delete the file manually and retry.)r%   r'   )r1   r2   r3   r4   r5   Úget_filenamer   ÚpathÚbasenameÚjoinÚexistsÚgetsizeÚRuntimeErrorr7   r   r6   ÚopenÚvalidate_filer?   Úwrite)r$   rA   rB   rC   rD   r'   rE   r<   Zreq_infoÚfilepathÚmodeZ
local_sizeÚfile_objZfpointerr>   r   r   r   Údownload_urli   s@    ÿ.ÿÿ.ÿÿrV   )rU   rC   rD   r   c                 C   sP   |dkrt  ¡ }n|dkr$t  ¡ }nt‚|  d¡}|s8qD| |¡ q(| ¡ |kS )a8  Validate a given file object with its hash.

    Args:
        file_obj: File object to read from.
        hash_value (str): Hash for url.
        hash_type (str, optional): Hash type, among "sha256" and "md5" (Default: ``"sha256"``).

    Returns:
        bool: return True if its a valid file, else False.
    r@   Úmd5i   )Úhashlibr@   rW   Ú
ValueErrorr9   r;   Ú	hexdigest)rU   rC   rD   Z	hash_funcr>   r   r   r   rQ   ¥   s    


rQ   )Ú	from_pathÚto_pathÚ	overwriter   c                 C   sŒ  |du rt j | ¡}z¤t | d¡�„}t d | ¡¡ g }|D ]T}t j ||j	¡}| 
¡ r„| |¡ t j |¡r„t d |¡¡ |s„q<| ||¡ q<|W  d  ƒ W S 1 s¬0    Y  W n tjyÌ   Y n0 zšt | d¡�v}t d | ¡¡ | ¡ }|D ]H}t j ||¡}t j |¡�r4t d |¡¡ |�s4� qú| ||¡ � qúW d  ƒ n1 �sZ0    Y  |W S  tj�y~   Y n0 tdƒ‚dS )a«  Extract archive.
    Args:
        from_path (str): the path of the archive.
        to_path (str, optional): the root path of the extraced files (directory of from_path) (Default: ``None``)
        overwrite (bool, optional): overwrite existing files (Default: ``False``)

    Returns:
        list: List of paths to extracted files even if not overwritten.

    Examples:
        >>> url = 'http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/validation.tar.gz'
        >>> from_path = './validation.tar.gz'
        >>> to_path = './'
        >>> torchaudio.datasets.utils.download_from_url(url, from_path)
        >>> torchaudio.datasets.utils.extract_archive(from_path, to_path)
    NÚrzOpened tar file {}.z{} already extracted.zOpened zip file {}.z7We currently only support tar.gz, tgz, and zip achives.)r   rJ   ÚdirnameÚtarfilerP   Úloggingr5   r7   rL   ÚnameÚisfileÚappendrM   ÚextractÚ	ReadErrorÚzipfileÚZipFileÚnamelistÚ
BadZipFileÚNotImplementedError)r[   r\   r]   ÚtarÚfilesÚfile_Ú	file_pathÚzfiler   r   r   Úextract_archiveÂ   sB    
(0rq   )ÚrootÚsuffixÚprefixÚremove_suffixr   c                 c   sx   t j | ¡} t  | ¡D ]\\}}}| ¡  | ¡  |D ]<}| |¡r4|rX|dt|ƒ … }|rjt j ||¡}|V  q4qdS )a•  List recursively 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 full path to each result, otherwise
            only returns the name of the files found (Default: ``False``)
        remove_suffix (bool, optional): If true, removes the suffix to each result defined in suffix,
            otherwise will return the result as found (Default: ``False``).
    N)r   rJ   Ú
expanduserÚwalkÚsortÚendswithr:   rL   )rr   rs   rt   ru   r   Údirsrm   Úfr   r   r   Ú
walk_filesú   s    
r|   c                   @   sB   e Zd ZdZdeeddœdd„Zeedœdd	„Z	ed
œdd„Z
dS )Ú
_DiskCachezW
    Wrap a dataset so that, whenever a new item is returned, it is saved to disk.
    ú.cachedN©ÚdatasetÚlocationr   c                 C   s*   || _ || _t| ƒ| _d gt|ƒ | _d S ©N)r€   r�   ÚidÚ_idr:   Ú_cache)Úselfr€   r�   r   r   r   Ú__init__#  s    
z_DiskCache.__init__)Únr   c                 C   sr   | j | r| j | }t |¡S t| jƒd t|ƒ }tj | j|¡}| j	| }|| j |< t
| jƒ t ||¡ |S )Nú-)r…   ÚtorchÚloadÚstrr„   r   rJ   rL   r�   r€   r"   Úsave)r†   rˆ   r{   Úitemr   r   r   Ú__getitem__*  s    





z_DiskCache.__getitem__©r   c                 C   s
   t | jƒS r‚   )r:   r€   ©r†   r   r   r   Ú__len__9  s    z_DiskCache.__len__)r~   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r
   rŒ   r‡   r   r   r�   r’   r   r   r   r   r}     s   r}   r~   r   c                 C   s
   t | |ƒS r‚   )r}   )r€   r�   r   r   r   Údiskcache_iterator=  s    r—   c                   @   sh   e Zd ZdZG dd„ dƒZeeddœdd„Zddœd	d
„Ze	dœdd„Z
e	dœdd„Ze	dœdd„ZdS )Ú_ThreadedIteratorzž
    Prefetch the next queue_length items from iterator in a background thread.

    Example:
    >> for i in bg_iterator(range(10)):
    >>     print(i)
    c                   @   s   e Zd ZdS )z_ThreadedIterator._EndN)r“   r”   r•   r   r   r   r   Ú_EndJ  s   r™   N)Ú	generatorr   r   c                 C   s.   t j | ¡ t|ƒ| _|| _d| _|  ¡  d S )NT)Ú	threadingÚThreadr‡   r   Úqueuerš   ÚdaemonÚstart)r†   rš   r   r   r   r   r‡   M  s
    
z_ThreadedIterator.__init__r�   c                 C   s*   | j D ]}| j |¡ q| j | j¡ d S r‚   )rš   r�   Úputr™   )r†   rŽ   r   r   r   ÚrunT  s    
z_ThreadedIterator.runc                 C   s   | S r‚   r   r‘   r   r   r   Ú__iter__Y  s    z_ThreadedIterator.__iter__c                 C   s   | j  ¡ }|| jkrt‚|S r‚   )r�   r6   r™   ÚStopIteration)r†   Z	next_itemr   r   r   Ú__next__\  s    

z_ThreadedIterator.__next__c                 C   s   |   ¡ S r‚   )r¤   r‘   r   r   r   Únextc  s    z_ThreadedIterator.next)r“   r”   r•   r–   r™   r   r   r‡   r¡   r   r¢   r¤   r¥   r   r   r   r   r˜   A  s   r˜   )Úiterabler   r   c                 C   s   t | |d�S )N)r   )r˜   )r¦   r   r   r   r   Úbg_iteratorg  s    r§   )Nr#   T)NNr@   TF)r@   )NF)FF)r~   )*r   r   rX   ra   r   r   r`   r›   rg   Ú_ior   r�   r   Útypingr   r   r   r   r   r	   rŠ   r1   Úurllib.requestZtorch.utils.datar
   Ztorch.utils.model_zoor   r   rŒ   r"   r   Úboolr?   rV   rQ   rq   r|   r}   r—   rœ   r˜   r§   r   r   r   r   Ú<module>   sh       ýý+     úú<:  ýý$&