o
    ^i"                     @   sx  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 d dl	m
Z
mZmZ d dlZddlmZ ddlmZmZmZ d	d
ddZdZG dd deZd"deeef dee deeeef ee f fddZdeeef dededdfddZd"deeef dee ddfddZd#deeef dee deddfddZ	d$deeef dee deee  deddf
d d!ZdS )%    N)Iterator)contextmanager)Path)AnyOptionalUnion   )ImageFolder)check_integrityextract_archiveverify_str_arg)zILSVRC2012_img_train.tar 1d675b47d978889d74fa0da5fadfb00e)zILSVRC2012_img_val.tar 29b22e2961454d5413ddabcf34fc5622)zILSVRC2012_devkit_t12.tar.gz fa75699e90414af021442c21a62c3abf)trainvaldevkitzmeta.binc                	       sf   e Zd ZdZddeeef dededdf fdd	Zdd
dZ	e
defddZdefddZ  ZS )ImageNeta<  `ImageNet <http://image-net.org/>`_ 2012 Classification Dataset.

    .. note::
        Before using this class, it is required to download ImageNet 2012 dataset from
        `here <https://image-net.org/challenges/LSVRC/2012/2012-downloads.php>`_ and
        place the files ``ILSVRC2012_devkit_t12.tar.gz`` and ``ILSVRC2012_img_train.tar``
        or ``ILSVRC2012_img_val.tar`` based on ``split`` in the root directory.

    Args:
        root (str or ``pathlib.Path``): Root directory of the ImageNet Dataset.
        split (string, optional): The dataset split, supports ``train``, or ``val``.
        transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader,
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
        loader (callable, optional): A function to load an image given its path.
            By default, it uses PIL as its image loader, but users could also pass in
            ``torchvision.io.decode_image`` for decoding image data into tensors directly.

     Attributes:
        classes (list): List of the class name tuples.
        class_to_idx (dict): Dict with items (class_name, class_index).
        wnids (list): List of the WordNet IDs.
        wnid_to_idx (dict): Dict with items (wordnet_id, class_index).
        imgs (list): List of (image path, class_index) tuples
        targets (list): The class_index value for each image in the dataset
    r   rootsplitkwargsreturnNc                    s   t j| }| _t|dd| _|   t| jd  t j	| j
fi | || _| j| _| j| _ fdd| jD | _dd t| jD | _d S )Nr   )r   r   r   c                       g | ]} | qS  r   ).0wnidwnid_to_classesr   X/var/www/html/RAG/RAG_venv/lib/python3.10/site-packages/torchvision/datasets/imagenet.py
<listcomp>@       z%ImageNet.__init__.<locals>.<listcomp>c                 S   s    i | ]\}}|D ]}||qqS r   r   )r   idxclssclsr   r   r   
<dictcomp>A        z%ImageNet.__init__.<locals>.<dictcomp>)ospath
expanduserr   r   r   parse_archivesload_meta_filesuper__init__split_folderclasseswnidsclass_to_idxwnid_to_idx	enumerate)selfr   r   r   	__class__r   r   r,   4   s   zImageNet.__init__c                 C   sd   t tj| jtst| j tj| js.| j	dkr"t
| j d S | j	dkr0t| j d S d S d S )Nr   r   )r
   r&   r'   joinr   	META_FILEparse_devkit_archiveisdirr-   r   parse_train_archiveparse_val_archiver3   r   r   r   r)   C   s   


zImageNet.parse_archivesc                 C   s   t j| j| jS N)r&   r'   r6   r   r   r<   r   r   r   r-   M   s   zImageNet.split_folderc                 C   s   dj di | jS )NzSplit: {split}r   )format__dict__r<   r   r   r   
extra_reprQ   s   zImageNet.extra_repr)r   )r   N)__name__
__module____qualname____doc__r   strr   r   r,   r)   propertyr-   r@   __classcell__r   r   r4   r   r      s    (

r   r   filer   c                 C   sD   |d u rt }tj| |}t|rtj|ddS d}t||| )NT)weights_onlyzThe meta file {} is not present in the root directory or is corrupted. This file is automatically created by the ImageNet dataset.)	r7   r&   r'   r6   r
   torchloadRuntimeErrorr>   )r   rH   msgr   r   r   r*   U   s   r*   md5c                 C   s,   t tj| ||sd}t||| d S )Nz{The archive {} is not present in the root directory or is corrupted. You need to download it externally and place it in {}.)r
   r&   r'   r6   rL   r>   )r   rH   rN   rM   r   r   r   _verify_archived   s
   rO   c              
      s(  ddl m dtdttttf ttttdf f f ffdd}dtdtt fdd	}tdtt fd
d}t	d }|du rC|d }|d }t
| || | :}ttj| || tj|d}||\ }	||}
 fdd|
D }t|	|ftj| t W d   dS 1 sw   Y  dS )aI  Parse the devkit archive of the ImageNet2012 classification dataset and save
    the meta information in a binary file.

    Args:
        root (str or ``pathlib.Path``): Root directory containing the devkit archive
        file (str, optional): Name of devkit archive. Defaults to
            'ILSVRC2012_devkit_t12.tar.gz'
    r   Ndevkit_rootr   .c                    s   t j| dd}j|ddd  tt  d } fddt|D  tt  d d	 \}}}d
d |D }dd t||D }dd t||D }||fS )Ndatazmeta.matT)
squeeze_mesynsets   c                    s    g | ]\}}|d kr | qS )r   r   )r   r!   num_childrenmetar   r   r   |   r%   z@parse_devkit_archive.<locals>.parse_meta_mat.<locals>.<listcomp>   c                 S   s   g | ]	}t |d qS )z, )tupler   )r   r"   r   r   r   r   ~       c                 S      i | ]\}}||qS r   r   )r   r!   r   r   r   r   r$          z@parse_devkit_archive.<locals>.parse_meta_mat.<locals>.<dictcomp>c                 S   r[   r   r   )r   r   r"   r   r   r   r$      r\   )r&   r'   r6   loadmatlistzipr2   )rP   metafilenums_childrenidcsr/   r.   idx_to_wnidr   )siorV   r   parse_meta_matx   s   z,parse_devkit_archive.<locals>.parse_meta_matc                 S   sN   t j| dd}t|}| }W d    n1 sw   Y  dd |D S )NrQ   z&ILSVRC2012_validation_ground_truth.txtc                 S   s   g | ]}t |qS r   )int)r   val_idxr   r   r   r      r    zKparse_devkit_archive.<locals>.parse_val_groundtruth_txt.<locals>.<listcomp>)r&   r'   r6   open	readlines)rP   rH   txtfhval_idcsr   r   r   parse_val_groundtruth_txt   s
   

z7parse_devkit_archive.<locals>.parse_val_groundtruth_txtc               	   s   s.    t  } z| V  W t|  d S t|  w r=   )tempfilemkdtempshutilrmtree)tmp_dirr   r   r   get_tmp_dir   s
   z)parse_devkit_archive.<locals>.get_tmp_dirr   r   ILSVRC2012_devkit_t12c                    r   r   r   )r   r!   )rc   r   r   r      r    z(parse_devkit_archive.<locals>.<listcomp>)scipy.ioiorE   rY   dictrf   r^   r   r   ARCHIVE_METArO   r   r&   r'   r6   rJ   saver7   )r   rH   re   rl   rr   archive_metarN   rq   rP   r   rk   	val_wnidsr   )rc   rd   r   r8   m   s$   	6"r8   r   folderc                    s   t d }|du r|d }|d }t| || tj| | ttj| |   fddt D }|D ]}t|tj|d dd q5dS )	a  Parse the train images archive of the ImageNet2012 classification dataset and
    prepare it for usage with the ImageNet dataset.

    Args:
        root (str or ``pathlib.Path``): Root directory containing the train images archive
        file (str, optional): Name of train images archive. Defaults to
            'ILSVRC2012_img_train.tar'
        folder (str, optional): Optional name for train images folder. Defaults to
            'train'
    r   Nr   r   c                    s   g | ]	}t j |qS r   r&   r'   r6   )r   archive
train_rootr   r   r      rZ   z'parse_train_archive.<locals>.<listcomp>T)remove_finished)rw   rO   r&   r'   r6   r   listdirsplitext)r   rH   r{   ry   rN   archivesr}   r   r~   r   r:      s   r:   r   r/   c           	         s   t d }|du r|d }|d }|du rt| d }t| || tj| | ttj| |  t fddt D }t	|D ]}t
tj | qCt||D ]\}}t|tj |tj| qUdS )az  Parse the validation images archive of the ImageNet2012 classification dataset
    and prepare it for usage with the ImageNet dataset.

    Args:
        root (str or ``pathlib.Path``): Root directory containing the validation images archive
        file (str, optional): Name of validation images archive. Defaults to
            'ILSVRC2012_img_val.tar'
        wnids (list, optional): List of WordNet IDs of the validation images. If None
            is given, the IDs are loaded from the meta file in the root directory
        folder (str, optional): Optional name for validation images folder. Defaults to
            'val'
    r   Nr   r   c                 3   s    | ]
}t j |V  qd S r=   r|   )r   imageval_rootr   r   	<genexpr>   s    z$parse_val_archive.<locals>.<genexpr>)rw   r*   rO   r&   r'   r6   r   sortedr   setmkdirr_   ro   movebasename)	r   rH   r/   r{   ry   rN   imagesr   img_filer   r   r   r;      s   "r;   r=   )Nr   )NNr   ) r&   ro   rm   collections.abcr   
contextlibr   pathlibr   typingr   r   r   rJ   r{   r	   utilsr
   r   r   rw   r7   r   rE   rY   rv   r^   r*   rO   r8   r:   r;   r   r   r   r   <module>   s@    8>"$	(6

