a
    áñh7S  ã                	   @   sÊ  d dl mZ ddlZddlm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 d dlmZmZmZmZ G dd„ deƒZG d	d
„ d
eƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZ e!e"dœdd„Z#ee$ef eeej%f dœdd„Z&e	j'ej'ej'fe	j(ej(ej(fe	j)e *d¡dfe	j+e *d¡dfe	j,e *d¡dfe	j-e *d¡dfdœZ.d(ee$ef e/e	j0d!œd"d#„Z1e$e	j0dœd$d%„Z2e$e	j0dœd&d'„Z3dS ))é   )ÚVisionDataseté    N)ÚImage)ÚAnyÚCallableÚDictÚIOÚListÚOptionalÚTupleÚUnion)Údownload_urlÚdownload_and_extract_archiveÚextract_archiveÚverify_str_argc                       s  e Zd ZdZg d¢ZdZdZg d¢Zedd„ ƒZ	edd	„ ƒZ
ed
d„ ƒZedd„ ƒZd&eeee ee eddœ‡ fdd„Zeeeef dœdd„Zedœdd„Zeedœdd„ƒZeedœdd„ƒZeeeef dœdd„ƒZedœd d!„Zddœd"d#„Zedœd$d%„Z‡  ZS )'ÚMNISTa3  `MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset.

    Args:
        root (string): Root directory of dataset where ``MNIST/processed/training.pt``
            and  ``MNIST/processed/test.pt`` exist.
        train (bool, optional): If True, creates dataset from ``training.pt``,
            otherwise from ``test.pt``.
        download (bool, optional): If true, downloads the dataset from the internet and
            puts it in root directory. If dataset is already downloaded, it is not
            downloaded again.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
    ))z;http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gzZ f68b3c2dcbeaaa9fbdd348bbdeb94873)z;http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gzZ d53e105ee54ea40749a09fcbcd1e9432)z:http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gzZ 9fb629c4189551a2d022fa330f9573f3)z:http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gzZ ec29112dd5afa0611ce80d1b7f02629cztraining.ptztest.pt©
z0 - zeroz1 - onez2 - twoz	3 - threez4 - fourz5 - fivez6 - sixz	7 - sevenz	8 - eightz9 - ninec                 C   s   t  d¡ | jS )Nz%train_labels has been renamed targets©ÚwarningsÚwarnÚtargets©Úself© r   úZ/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchvision/datasets/mnist.pyÚtrain_labels.   s    
zMNIST.train_labelsc                 C   s   t  d¡ | jS )Nz$test_labels has been renamed targetsr   r   r   r   r   Útest_labels3   s    
zMNIST.test_labelsc                 C   s   t  d¡ | jS )Nz train_data has been renamed data©r   r   Údatar   r   r   r   Ú
train_data8   s    
zMNIST.train_datac                 C   s   t  d¡ | jS )Nztest_data has been renamed datar   r   r   r   r   Ú	test_data=   s    
zMNIST.test_dataTNF)ÚrootÚtrainÚ	transformÚtarget_transformÚdownloadÚreturnc                    sn   t t| ƒj|||d� || _|r(|  ¡  |  ¡ s8tdƒ‚| jrF| j}n| j}t	 
tj | j|¡¡\| _| _d S )N)r#   r$   z;Dataset not found. You can use download=True to download it)Úsuperr   Ú__init__r"   r%   Ú_check_existsÚRuntimeErrorÚtraining_fileÚ	test_fileÚtorchÚloadÚosÚpathÚjoinÚprocessed_folderr   r   )r   r!   r"   r#   r$   r%   Ú	data_file©Ú	__class__r   r   r(   B   s    ÿzMNIST.__init__©Úindexr&   c                 C   s\   | j | t| j| ƒ }}tj| ¡ dd�}| jdur@|  |¡}| jdurT|  |¡}||fS )z–
        Args:
            index (int): Index

        Returns:
            tuple: (image, target) where target is index of the target class.
        ÚL©ÚmodeN)r   Úintr   r   Ú	fromarrayÚnumpyr#   r$   ©r   r7   ÚimgÚtargetr   r   r   Ú__getitem__[   s    



zMNIST.__getitem__©r&   c                 C   s
   t | jƒS ©N)Úlenr   r   r   r   r   Ú__len__q   s    zMNIST.__len__c                 C   s   t j | j| jjd¡S )NÚraw©r/   r0   r1   r!   r5   Ú__name__r   r   r   r   Ú
raw_foldert   s    zMNIST.raw_folderc                 C   s   t j | j| jjd¡S )NÚ	processedrG   r   r   r   r   r2   x   s    zMNIST.processed_folderc                 C   s   dd„ t | jƒD ƒS )Nc                 S   s   i | ]\}}||“qS r   r   )Ú.0ÚiÚ_classr   r   r   Ú
<dictcomp>~   ó    z&MNIST.class_to_idx.<locals>.<dictcomp>)Ú	enumerateÚclassesr   r   r   r   Úclass_to_idx|   s    zMNIST.class_to_idxc                 C   s4   t j t j | j| j¡¡o2t j t j | j| j¡¡S rC   )r/   r0   Úexistsr1   r2   r+   r,   r   r   r   r   r)   €   s    ÿÿþzMNIST._check_existsc                 C   sJ  |   ¡ rdS tj| jdd� tj| jdd� | jD ](\}}| d¡d }t|| j||d� q2tdƒ t	tj
 | jd¡ƒttj
 | jd	¡ƒf}t	tj
 | jd
¡ƒttj
 | jd¡ƒf}ttj
 | j| j¡dƒ�}t ||¡ W d  ƒ n1 sî0    Y  ttj
 | j| j¡dƒ�}t ||¡ W d  ƒ n1 �s40    Y  tdƒ dS )zHDownload the MNIST data if it doesn't exist in processed_folder already.NT©Úexist_okú/é   )Údownload_rootÚfilenameÚmd5úProcessing...ztrain-images-idx3-ubyteztrain-labels-idx1-ubytezt10k-images-idx3-ubytezt10k-labels-idx1-ubyteÚwbúDone!)r)   r/   ÚmakedirsrI   r2   Ú	resourcesÚ
rpartitionr   ÚprintÚread_image_filer0   r1   Úread_label_fileÚopenr+   r-   Úsaver,   )r   ÚurlrZ   rY   Útraining_setÚtest_setÚfr   r   r   r%   †   s&    þþ*,zMNIST.downloadc                 C   s   d  | jdu rdnd¡S )Nú	Split: {}TZTrainZTest)Úformatr"   r   r   r   r   Ú
extra_repr¦   s    zMNIST.extra_repr)TNNF)rH   Ú
__module__Ú__qualname__Ú__doc__r_   r+   r,   rQ   Úpropertyr   r   r   r    ÚstrÚboolr
   r   r(   r;   r   r   rA   rE   rI   r2   r   rR   r)   r%   rl   Ú__classcell__r   r   r4   r   r      sH   



    úù r   c                   @   s    e Zd ZdZg d¢Zg d¢ZdS )ÚFashionMNISTaX  `Fashion-MNIST <https://github.com/zalandoresearch/fashion-mnist>`_ Dataset.

    Args:
        root (string): Root directory of dataset where ``FashionMNIST/processed/training.pt``
            and  ``FashionMNIST/processed/test.pt`` exist.
        train (bool, optional): If True, creates dataset from ``training.pt``,
            otherwise from ``test.pt``.
        download (bool, optional): If true, downloads the dataset from the internet and
            puts it in root directory. If dataset is already downloaded, it is not
            downloaded again.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
    ))zUhttp://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gzZ 8d4fb7e6c68d591d4c3dfef9ec88bf0d)zUhttp://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gzZ 25c81989df183df01b3e8a0aad5dffbe)zThttp://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gzZ bef4ecab320f06d8554ea6380940ec79)zThttp://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gzZ bb300cfdad3c16e7a12a480ee83cd310)
zT-shirt/topZTrouserZPulloverZDressZCoatZSandalZShirtZSneakerZBagz
Ankle bootN©rH   rm   rn   ro   r_   rQ   r   r   r   r   rt   ª   s   
rt   c                   @   s    e Zd ZdZg d¢Zg d¢ZdS )ÚKMNISTaA  `Kuzushiji-MNIST <https://github.com/rois-codh/kmnist>`_ Dataset.

    Args:
        root (string): Root directory of dataset where ``KMNIST/processed/training.pt``
            and  ``KMNIST/processed/test.pt`` exist.
        train (bool, optional): If True, creates dataset from ``training.pt``,
            otherwise from ``test.pt``.
        download (bool, optional): If true, downloads the dataset from the internet and
            puts it in root directory. If dataset is already downloaded, it is not
            downloaded again.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
    ))zGhttp://codh.rois.ac.jp/kmnist/dataset/kmnist/train-images-idx3-ubyte.gzZ bdb82020997e1d708af4cf47b453dcf7)zGhttp://codh.rois.ac.jp/kmnist/dataset/kmnist/train-labels-idx1-ubyte.gzZ e144d726b3acfaa3e44228e80efcd344)zFhttp://codh.rois.ac.jp/kmnist/dataset/kmnist/t10k-images-idx3-ubyte.gzZ 5c965bf0a639b31b8f53240b1b52f4d7)zFhttp://codh.rois.ac.jp/kmnist/dataset/kmnist/t10k-labels-idx1-ubyte.gzZ 7320c461ea6c1c855c0b718fb2a4b134)
ÚoZkiZsuZtsuÚnaZhaÚmaZyaÚreZwoNru   r   r   r   r   rv   È   s   rv   c                       sÊ   e Zd ZdZdZdZdZeg d¢ƒZee	e
je
j ƒƒZe	eƒee	ee ƒƒee	ee ƒƒe	e
jƒe	e
jƒe	e
jƒdœZeeeddœ‡ fdd	„Zeed
œdd„ƒZeed
œdd„ƒZdd
œdd„Z‡  ZS )ÚEMNISTa)  `EMNIST <https://www.westernsydney.edu.au/bens/home/reproducible_research/emnist>`_ Dataset.

    Args:
        root (string): Root directory of dataset where ``EMNIST/processed/training.pt``
            and  ``EMNIST/processed/test.pt`` exist.
        split (string): The dataset has 6 different splits: ``byclass``, ``bymerge``,
            ``balanced``, ``letters``, ``digits`` and ``mnist``. This argument specifies
            which one to use.
        train (bool, optional): If True, creates dataset from ``training.pt``,
            otherwise from ``test.pt``.
        download (bool, optional): If true, downloads the dataset from the internet and
            puts it in root directory. If dataset is already downloaded, it is not
            downloaded again.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
    z9http://www.itl.nist.gov/iaui/vip/cs_links/EMNIST/gzip.zipZ 58c8d27c78d21e728a6bc7b3cc06412e)ZbyclassZbymergeZbalancedÚlettersÚdigitsZmnist)ÚCÚIÚJÚKr8   ÚMÚOÚPÚSÚUÚVÚWÚXÚYÚZN)r!   ÚsplitÚkwargsr&   c                    sR   t |d| jƒ| _|  |¡| _|  |¡| _tt| ƒj	|fi |¤Ž | j
| j | _d S )NrŒ   )r   ÚsplitsrŒ   Ú_training_filer+   Ú
_test_filer,   r'   r{   r(   Úclasses_split_dictrQ   )r   r!   rŒ   r�   r4   r   r   r(     s
    zEMNIST.__init__rB   c                 C   s
   d  | ¡S )Nztraining_{}.pt©rk   ©rŒ   r   r   r   r�     s    zEMNIST._training_filec                 C   s
   d  | ¡S )Nz
test_{}.ptr’   r“   r   r   r   r�     s    zEMNIST._test_filec              	   C   s¶  ddl }|  ¡ rdS tj| jdd� tj| jdd� tdƒ t| j| jdd| j	d� tj
 | jd¡}t |¡D ]"}| d	¡rnttj
 ||¡|ƒ qn| jD �]}td
| ƒ ttj
 |d |¡¡ƒttj
 |d |¡¡ƒf}ttj
 |d |¡¡ƒttj
 |d |¡¡ƒf}ttj
 | j|  |¡¡dƒ�}t ||¡ W d  ƒ n1 �sJ0    Y  ttj
 | j|  |¡¡dƒ�}t ||¡ W d  ƒ q˜1 �s”0    Y  q˜| |¡ tdƒ dS )zIDownload the EMNIST data if it doesn't exist in processed_folder already.r   NTrT   z&Downloading and extracting zip archivez
emnist.zip)rX   rY   Zremove_finishedrZ   Úgzipú.gzzProcessing z!emnist-{}-train-images-idx3-ubytez!emnist-{}-train-labels-idx1-ubytez emnist-{}-test-images-idx3-ubytez emnist-{}-test-labels-idx1-ubyter\   r]   )Úshutilr)   r/   r^   rI   r2   ra   r   rf   rZ   r0   r1   ÚlistdirÚendswithr   rŽ   rb   rk   rc   rd   r�   r-   re   r�   Úrmtree)r   r–   Zgzip_folderZ	gzip_filerŒ   rg   rh   ri   r   r   r   r%     s6    ÿ
þþ,.
zEMNIST.download)rH   rm   rn   ro   rf   rZ   rŽ   ÚsetZ_merged_classesÚlistÚstringr}   Úascii_lettersZ_all_classesÚsortedÚascii_lowercaser‘   rq   r   r(   Ústaticmethodr�   r�   r%   rs   r   r   r4   r   r{   á   s&   ú	r{   c                       s¸   e Zd ZU dZddddddœZddgdd	gd
dgdœZeeee	eef  f e
d< g d¢Zdeee eeeddœ‡ fdd„Zddœdd„Zee	eef dœdd„Zedœdd„Z‡  ZS )ÚQMNISTa_  `QMNIST <https://github.com/facebookresearch/qmnist>`_ Dataset.

    Args:
        root (string): Root directory of dataset whose ``processed''
            subdir contains torch binary files with the datasets.
        what (string,optional): Can be 'train', 'test', 'test10k',
            'test50k', or 'nist' for respectively the mnist compatible
            training set, the 60k qmnist testing set, the 10k qmnist
            examples that match the mnist testing set, the 50k
            remaining qmnist testing examples, or all the nist
            digits. The default is to select 'train' or 'test'
            according to the compatibility argument 'train'.
        compat (bool,optional): A boolean that says whether the target
            for each example is class number (for compatibility with
            the MNIST dataloader) or a torch vector containing the
            full qmnist information. Default=True.
        download (bool, optional): If true, downloads the dataset from
            the internet and puts it in root directory. If dataset is
            already downloaded, it is not downloaded again.
        transform (callable, optional): A function/transform that
            takes in an PIL image and returns a transformed
            version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform
            that takes in the target and transforms it.
        train (bool,optional,compatibility): When argument 'what' is
            not specified, this boolean decides whether to load the
            training set ot the testing set.  Default: True.

    r"   ÚtestÚnist)r"   r¢   Útest10kÚtest50kr£   )zbhttps://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-train-images-idx3-ubyte.gzZ ed72d4157d28c017586c42bc6afe6370)z`https://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-train-labels-idx2-int.gzZ 0058f8dd561b90ffdd0f734c6a30e5e4)zahttps://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-test-images-idx3-ubyte.gzZ 1394631089c404de565df7b7aeaf9412)z_https://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-test-labels-idx2-int.gzZ 5b5b05890a5e13444e108efe57b788aa)z[https://raw.githubusercontent.com/facebookresearch/qmnist/master/xnist-images-idx3-ubyte.xzZ 7f124b3b8ab81486c9d8c2749c17f834)zYhttps://raw.githubusercontent.com/facebookresearch/qmnist/master/xnist-labels-idx2-int.xzZ 5ed0e788978e45d4a8bd4b7caec3d79d)r"   r¢   r£   r_   r   NT)r!   ÚwhatÚcompatr"   r�   r&   c                    sj   |d u r|rdnd}t |dt| j ¡ ƒƒ| _|| _|d | _| j| _| j| _t	t
| ƒj||fi |¤Ž d S )Nr"   r¢   r¦   z.pt)r   ÚtupleÚsubsetsÚkeysr¦   r§   r3   r+   r,   r'   r¡   r(   )r   r!   r¦   r§   r"   r�   r4   r   r   r(   t  s    
zQMNIST.__init__rB   c           
      C   s¼  |   ¡ rdS tj| jdd� tj| jdd� | j| j| j  }g }|D ]N\}}| d¡d }tj	 
| j|¡}tj	 |¡sŠt|| j||d� | |¡ qFtdƒ t|d ƒ}|jtjksºJ ‚| ¡ d	ksÊJ ‚t|d
 ƒ ¡ }| ¡ dksêJ ‚| jdk�r,|dd…dd…dd…f  ¡ }|dd…dd…f  ¡ }| jdk�rn|dd…dd…dd…f  ¡ }|dd…dd…f  ¡ }ttj	 
| j| j¡dƒ� }	t ||f|	¡ W d  ƒ n1 �s®0    Y  dS )z£Download the QMNIST data if it doesn't exist in processed_folder already.
           Note that we only download what has been asked for (argument 'what').
        NTrT   rV   rW   )r!   rY   rZ   r[   r   é   r   r¤   i'  r¥   r\   )r)   r/   r^   rI   r2   r_   r©   r¦   r`   r0   r1   Úisfiler   Úappendra   Úread_sn3_pascalvincent_tensorÚdtyper-   Úuint8Ú
ndimensionÚlongÚclonerd   r3   re   )
r   rŒ   Úfilesrf   rZ   rY   Ú	file_pathr   r   ri   r   r   r   r%   �  s4    zQMNIST.downloadr6   c                 C   sj   | j | | j|  }}tj| ¡ dd�}| jd ur<|  |¡}| jrNt|d ƒ}| jd urb|  |¡}||fS )Nr8   r9   r   )	r   r   r   r<   r=   r#   r§   r;   r$   r>   r   r   r   rA   ¤  s    



zQMNIST.__getitem__c                 C   s   d  | j¡S )Nrj   )rk   r¦   r   r   r   r   rl   °  s    zQMNIST.extra_repr)NTT)rH   rm   rn   ro   r©   r_   r   rq   r	   r   Ú__annotations__rQ   r
   rr   r   r(   r%   r;   rA   rl   rs   r   r   r4   r   r¡   =  s8   
ûþþþ÷"  þ
ý#r¡   )Úbr&   c                 C   s   t t | d¡dƒS )NÚhexé   )r;   ÚcodecsÚencode)r·   r   r   r   Úget_int´  s    r¼   )r0   r&   c                 C   sH   t | tjjƒs| S |  d¡r(t | d¡S |  d¡r>t | d¡S t| dƒS )z¢Return a file object that possibly decompresses 'path' on the fly.
       Decompression occurs when argument `path` is a string and ends with '.gz' or '.xz'.
    r•   Úrbz.xz)Ú
isinstancer-   Z_sixZstring_classesr˜   r”   rd   Úlzma)r0   r   r   r   Úopen_maybe_compressed_file¸  s    

rÀ   z>i2Úi2z>i4Úi4z>f4Zf4z>f8Zf8)é   é	   é   é   é   é   T)r0   Ústrictr&   c           	         sì   t | ƒ�}| ¡ ‰ W d  ƒ n1 s&0    Y  tˆ dd… ƒ}|d }|d }|dkr`|dksdJ ‚|dkrt|dksxJ ‚t| }‡ fd	d
„t|ƒD ƒ}tjˆ |d d|d  d�}|jd t |¡ksÎ|rÎJ ‚t	 
|j|d dd�¡j|Ž S )z˜Read a SN3 file in "Pascal Vincent" format (Lush file 'libidx/idx-io.lsh').
       Argument may be a filename, compressed filename, or file object.
    Nr   é   é   r   r«   rÃ   rÈ   c                    s,   g | ]$}t ˆ d |d  d |d  … ƒ‘qS )rÊ   r   rW   )r¼   )rK   rL   ©r   r   r   Ú
<listcomp>Ý  rO   z1read_sn3_pascalvincent_tensor.<locals>.<listcomp>)r¯   ÚoffsetrW   F)Úcopy)rÀ   Úreadr¼   ÚSN3_PASCALVINCENT_TYPEMAPÚrangeÚnpZ
frombufferÚshapeÚprodr-   Z
from_numpyZastypeÚview)	r0   rÉ   ri   ÚmagicZndÚtyÚmÚsÚparsedr   rÌ   r   r®   Ï  s    
&r®   c                 C   s^   t | dƒ�}t|dd�}W d   ƒ n1 s,0    Y  |jtjksFJ ‚| ¡ dksVJ ‚| ¡ S )Nr½   F©rÉ   r   )rd   r®   r¯   r-   r°   r±   r²   ©r0   ri   Úxr   r   r   rc   ã  s
    *rc   c                 C   sZ   t | dƒ�}t|dd�}W d   ƒ n1 s,0    Y  |jtjksFJ ‚| ¡ dksVJ ‚|S )Nr½   FrÜ   r«   )rd   r®   r¯   r-   r°   r±   rÝ   r   r   r   rb   ë  s
    *rb   )T)4Zvisionr   r   ZPILr   r/   Úos.pathr=   rÓ   r-   rº   rœ   r”   r¿   Útypingr   r   r   r   r	   r
   r   r   Úutilsr   r   r   r   r   rt   rv   r{   r¡   Úbytesr;   r¼   rq   ÚGzipFilerÀ   r°   Zint8Úint16r¯   Úint32Úfloat32Úfloat64rÑ   rr   ZTensorr®   rc   rb   r   r   r   r   Ú<module>   s<   ( \w"ú
