
    Yh"                        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e          Zddeeef         dee         deeeef         ee         f         fdZdeeef         dededdfdZddeeef         dee         ddfdZddeeef         dee         deddfdZ	 ddeeef         dee         deee                  deddf
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            	       v     e Zd ZdZddeeef         dededdf fdZdd	Z	e
defd
            ZdefdZ x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                    t           j                            |          x}| _        t	          |dd          | _        |                                  t          | j                  d          t                      j	        | j
        fi | || _        | j        | _        | j        | _        fd| j        D             | _        d t          | j                  D             | _        d S )Nr   )r   r   r   c                      g | ]
}|         S  r   ).0wnidwnid_to_classess     o/var/www/tools.fuzzalab.pt/emblema-extractor/venv/lib/python3.11/site-packages/torchvision/datasets/imagenet.py
<listcomp>z%ImageNet.__init__.<locals>.<listcomp>@   s    EEE$-EEE    c                 $    i | ]\  }}|D ]}||S r   r   )r   idxclssclss       r    
<dictcomp>z%ImageNet.__init__.<locals>.<dictcomp>A   s-    ___)#tZ^__SVS#____r"   )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   r   	__class__s       @r    r.   zImageNet.__init__4   s    7--d333ty#E74DEE
(33A6*55f555	\
,EEEE$*EEE__y7N7N___r"   c                 l   t          t          j                            | j        t
                              st          | j                   t          j                            | j                  sB| j	        dk    rt          | j                   d S | j	        dk    rt          | 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r5   s    r    r+   zImageNet.parse_archivesC   s    rw||DIyAABB 	, +++w}}T.// 	-zW$$#DI.....u$$!$),,,,,		- 	- %$r"   c                 V    t           j                            | j        | j                  S N)r(   r)   r8   r   r   r>   s    r    r/   zImageNet.split_folderM   s    w||DItz222r"   c                 &     dj         di | j        S )NzSplit: {split}r   )format__dict__r>   s    r    
extra_reprzImageNet.extra_reprQ   s    &&77777r"   )r   )r   N)__name__
__module____qualname____doc__r   strr   r   r.   r+   propertyr/   rD   __classcell__)r6   s   @r    r   r      s         8` `U39- `c `s `W[ ` ` ` ` ` `- - - - 3c 3 3 3 X38C 8 8 8 8 8 8 8 8r"   r   r   filer   c                     |t           }t          j                            | |          }t	          |          rt          j        |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.)	r9   r(   r)   r8   r   torchloadRuntimeErrorrB   )r   rL   msgs      r    r,   r,   U   so    |7<<d##Dt 3z$T2222J 	 3::dD11222r"   md5c                     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)   r8   rQ   rB   )r   rL   rS   rR   s       r    _verify_archiverU   d   sW    27<<d33S99 3E 	 3::dD112223 3r"   c           
      H   ddl m dt          dt          t          t
          t          f         t          t          t          t          df         f         f         ffd}dt          dt          t
                   fd}t          dt          t                   fd            }t          d	         }||d         }|d
         }t          | ||            |            5 }t          t          j                            | |          |           t          j                            |d          } ||          \  }	 ||          }
fd|
D             }t          j        |	|ft          j                            | t"                               ddd           dS # 1 swxY w 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                    t           j                            | dd          }	                    |d          d         t	          t                     d         }fdt          |          D             t	          t                     d d         \  }}}d	 |D             }d
 t          ||          D             }d t          ||          D             }||fS )Ndatazmeta.matT)
squeeze_mesynsets   c                 2    g | ]\  }}|d k    |         S )r   r   )r   r$   num_childrenmetas      r    r!   z@parse_devkit_archive.<locals>.parse_meta_mat.<locals>.<listcomp>|   s-    aaa/c<|_`O`O`S	O`O`O`r"      c                 R    g | ]$}t          |                    d                     %S )z, )tupler   )r   r%   s     r    r!   z@parse_devkit_archive.<locals>.parse_meta_mat.<locals>.<listcomp>~   s,    ???t5D))**???r"   c                     i | ]\  }}||	S r   r   )r   r$   r   s      r    r'   z@parse_devkit_archive.<locals>.parse_meta_mat.<locals>.<dictcomp>   s    CCCYS$sDCCCr"   c                     i | ]\  }}||	S r   r   )r   r   r%   s      r    r'   z@parse_devkit_archive.<locals>.parse_meta_mat.<locals>.<dictcomp>   s    LLL*$4LLLr"   )r(   r)   r8   loadmatlistzipr4   )
rW   metafilenums_childrenidcsr1   r0   idx_to_wnidr   r_   sios
           @r    parse_meta_matz,parse_devkit_archive.<locals>.parse_meta_matx   s    7<<VZ@@{{8{55i@S$Z((+aaaa9]3K3Kaaa#CJ//3eW??w???CC#dE2B2BCCCLLE78K8KLLLO++r"   c                     t           j                            | dd          }t          |          5 }|                                }d d d            n# 1 swxY w Y   d |D             S )NrY   z&ILSVRC2012_validation_ground_truth.txtc                 ,    g | ]}t          |          S r   )int)r   val_idxs     r    r!   zKparse_devkit_archive.<locals>.parse_val_groundtruth_txt.<locals>.<listcomp>   s    555G555r"   )r(   r)   r8   open	readlines)rW   rL   txtfhval_idcss       r    parse_val_groundtruth_txtz7parse_devkit_archive.<locals>.parse_val_groundtruth_txt   s    w||K1YZZ$ZZ 	)5((H	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)55H5555s   AAAc               3      K   t          j                    } 	 | V  t          j        |            d S # t          j        |            w xY wr@   )tempfilemkdtempshutilrmtree)tmp_dirs    r    get_tmp_dirz)parse_devkit_archive.<locals>.get_tmp_dir   sN      "$$	#MMMM'"""""FM'""""s	   1 Ar   r	   ILSVRC2012_devkit_t12c                      g | ]
}|         S r   r   )r   r$   rk   s     r    r!   z(parse_devkit_archive.<locals>.<listcomp>   s    :::#[%:::r"   )scipy.ioiorI   rb   dictrp   rf   r   r   ARCHIVE_METArU   r   r(   r)   r8   rO   saver9   )r   rL   rm   rv   r}   archive_metarS   r|   rW   r   ru   	val_wnidsrk   rl   s               @@r    r:   r:   m   s    	,C 	,E$sCx.$sERUWZRZOG[B\2\,] 	, 	, 	, 	, 	, 	,6s 6tCy 6 6 6 6 ## # # # ^#  )L|A
q/CD$$$$	 P'T400':::gll7,CDD'5~k'B'B$_,,[99:::::::	
OY/dI1N1NOOOP P P P P P P P P P P P P P P P P Ps   B0FFFr   folderc                    t           d         }||d         }|d         }t          | ||           t          j                            | |          t          t          j                            | |                     fdt          j                  D             }|D ]7}t          |t          j                            |          d         d           8d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                 P    g | ]"}t           j                            |          #S r   r(   r)   r8   )r   archive
train_roots     r    r!   z'parse_train_archive.<locals>.<listcomp>   s)    XXXgZ11XXXr"   T)remove_finished)r   rU   r(   r)   r8   r   listdirsplitext)r   rL   r   r   rS   archivesr   r   s          @r    r<   r<      s      (L|A
q/CD$$$$dF++JBGLLt,,j999XXXXJAWAWXXXH U U!1!1'!:!:1!=tTTTTTU Ur"   r   r1   c                   	 t           d         }||d         }|d         }|t          |           d         }t          | ||           t          j                            | |          	t          t          j                            | |          	           t          	fdt          j        	          D                       }t          |          D ]4}t          j
        t          j                            	|                     5t          ||          D ]V\  }}t          j        |t          j                            	|t          j                            |                               Wd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   X   K   | ]$}t           j                            |          V  %d S r@   r   )r   imageval_roots     r    	<genexpr>z$parse_val_archive.<locals>.<genexpr>   s3      TTeBGLL511TTTTTTr"   )r   r,   rU   r(   r)   r8   r   sortedr   setmkdirrg   rz   movebasename)
r   rL   r1   r   r   rS   imagesr   img_filer   s
            @r    r=   r=      sJ     &L|A
q/C}t$$Q'D$$$$w||D&))HBGLLt,,h777TTTTrz(?S?STTTTTFE

 / /
h--....eV,, X XhHbgll8T27;K;KH;U;UVVWWWWX Xr"   r@   )Nr   )NNr   ) r(   rz   rx   collections.abcr   
contextlibr   pathlibr   typingr   r   r   rO   r   r
   utilsr   r   r   r   r9   r   rI   rb   r   rf   r,   rU   r:   r<   r=   r   r"   r    <module>r      s   				   $ $ $ $ $ $ % % % % % %       ' ' ' ' ' ' ' ' ' '        C C C C C C C C C C NIR  	;8 ;8 ;8 ;8 ;8{ ;8 ;8 ;8|3 3sDy) 3# 3%PTUXZ]U]P^`deh`iPiJj 3 3 3 33%T	* 3# 3C 3D 3 3 3 33P 3PuS$Y/ 3Px} 3PPT 3P 3P 3P 3PlU UeCI. Uhsm UTW Ufj U U U U6 jo!X !X
T	
!X"*3-!X?GS	?R!Xcf!X	!X !X !X !X !X !Xr"   