
    h"                        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y)    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            	       j     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
    rootsplitkwargsreturnNc                    t         j                  j                  |      x}| _        t	        |dd      | _        | j                          t        | j                        d   }t        	| $  | j                  fi | || _        | j                  | _        | j                  | _        | j                  D cg c]  }||   	 c}| _        t        | j                        D ci c]  \  }}|D ]  }||  c}}}| _        y c c}w c c}}}w )Nr   )r   r   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   wnid_to_classeswnididxclsscls	__class__s
            [/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/torchvision/datasets/imagenet.pyr!   zImageNet.__init__4   s    77--d33ty#E74DE
(3A6**5f5	\\
,,:>**E$-E7@7N__)#tZ^_SVS#X_S_ F_s   3C? Dc                    t        t        j                  j                  | j                  t
                    st        | j                         t        j                  j                  | j                        sK| j                  dk(  rt        | j                         y | j                  dk(  rt        | j                         y y y )Nr   r   )r   r   r   joinr   	META_FILEparse_devkit_archiveisdirr"   r   parse_train_archiveparse_val_archiver(   s    r/   r   zImageNet.parse_archivesC   sy    rww||DIIyAB +ww}}T../zzW$#DII.u$!$)), % 0    c                 j    t         j                  j                  | j                  | j                        S N)r   r   r1   r   r   r7   s    r/   r"   zImageNet.split_folderM   s    ww||DIItzz22r8   c                 :     dj                   di | j                  S )NzSplit: {split} )format__dict__r7   s    r/   
extra_reprzImageNet.extra_reprQ   s    &&&777r8   )r   )r   N)__name__
__module____qualname____doc__r   strr   r   r!   r   propertyr"   r?   __classcell__)r.   s   @r/   r   r      sd    8`U39- `c `s `W[ `- 3c 3 38C 8r8   r   r   filer   c                     |t         }t        j                  j                  | |      }t	        |      rt        j                  |d      S d}t        |j                  ||             )NT)weights_onlyzThe meta file {} is not present in the root directory or is corrupted. This file is automatically created by the ImageNet dataset.)	r2   r   r   r1   r   torchloadRuntimeErrorr=   )r   rG   msgs      r/   r   r   U   s\    |77<<d#Dtzz$T22J 	 3::dD122r8   md5c                     t        t        j                  j                  | |      |      sd}t	        |j                  ||             y )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   r1   rL   r=   )r   rG   rN   rM   s       r/   _verify_archiverP   d   sC    277<<d3S9E 	 3::dD122 :r8   c           
         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                  j                  | |      |       t        j                  j                  |d      } ||      \  }	}
 ||      }|D cg c]  }|	|   	 }}t        j                   |
|ft        j                  j                  | t"                     ddd       yc c}w # 1 sw Y   yxY w)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                  j                  | dd      }j                  |d      d   }t	        t        |       d   }t        |      D cg c]  \  }}|dk(  s||    }}}t	        t        |       d d \  }}}|D 	cg c]  }	t        |	j                  d	             }}	t        ||      D 
ci c]  \  }}
||

 }}}
t        ||      D 
	ci c]  \  }
}	|
|	
 }}
}	||fS c c}}w c c}	w c c}
}w c c}	}
w )
Ndatazmeta.matT)
squeeze_mesynsets   r      z, )	r   r   r1   loadmatlistzipr'   tupler   )rR   metafilemetanums_childrenr+   num_childrenidcsr$   r#   r,   r*   idx_to_wnidr)   sios                r/   parse_meta_matz,parse_devkit_archive.<locals>.parse_meta_matx   s   77<<VZ@{{8{5i@S$Z(+3<]3Ka/c<|_`O`S	aa#CJ/3eW7>?t5D)*??25dE2BCYS$sDyCC8;E78KL*$4:LLO++ b?CLs   C4)C4!C:C? Dc                     t         j                  j                  | dd      }t        |      5 }|j	                         }d d d        D cg c]  }t        |       c}S # 1 sw Y   "xY wc c}w )NrT   z&ILSVRC2012_validation_ground_truth.txt)r   r   r1   open	readlinesint)rR   rG   txtfhval_idcsval_idxs        r/   parse_val_groundtruth_txtz7parse_devkit_archive.<locals>.parse_val_groundtruth_txt   sZ    ww||K1YZ$Z 	)5(H	),45G55	) 	)5s   A
A+A(c               3      K   t        j                         } 	 |  t        j                  |        y # t        j                  |        w xY wwr:   )tempfilemkdtempshutilrmtree)tmp_dirs    r/   get_tmp_dirz)parse_devkit_archive.<locals>.get_tmp_dir   s6     ""$	#MMM'"FMM'"s   A2 AA		Ar   r	   ILSVRC2012_devkit_t12)scipy.ioiorD   r\   dictrh   rZ   r   r   ARCHIVE_METArP   r   r   r   r1   rJ   saver2   )r   rG   rd   rl   rs   archive_metarN   rr   rR   rb   r)   rj   r+   	val_wnidsrc   s                 @r/   r3   r3   m   sS    	,C 	,E$sCx.$sERUWZRZOG[B\2\,] 	,6s 6tCy 6 ## # #  )L|A
q/CD$$	 P'T40':ggll7,CD'5k'B$_,[919:#[%:	:

OY/dI1NOP P ;P Ps   $A"EE<EEE%folderc                    t         d   }||d   }|d   }t        | ||       t        j                  j	                  | |      }t        t        j                  j	                  | |      |       t        j                  |      D cg c]"  }t        j                  j	                  ||      $ }}|D ]0  }t        |t        j                  j                  |      d   d       2 yc c}w )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	   T)remove_finished)rx   rP   r   r   r1   r   listdirsplitext)r   rG   r|   rz   rN   
train_rootarchivearchivess           r/   r5   r5      s      (L|A
q/CD$$dF+JBGGLLt,j9ACJAWXgZ1XHX U!1!1'!:1!=tTU Ys   'C#r$   c                   	 t         d   }||d   }|d   }|t        |       d   }t        | ||       t        j                  j                  | |      	t        t        j                  j                  | |      	       t        	fdt        j                  	      D              }t        |      D ]5  }t        j                  t        j                  j                  	|             7 t        ||      D ]W  \  }}t        j                  |t        j                  j                  	|t        j                  j                  |                   Y y)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   ^   K   | ]$  }t         j                  j                  |       & y wr:   )r   r   r1   ).0imageval_roots     r/   	<genexpr>z$parse_val_archive.<locals>.<genexpr>   s      TeBGGLL51Ts   *-)rx   r   rP   r   r   r1   r   sortedr   setmkdirr[   rp   movebasename)
r   rG   r$   r|   rz   rN   imagesr*   img_filer   s
            @r/   r6   r6      s     &L|A
q/C}t$Q'D$$ww||D&)HBGGLLt,h7Trzz(?STTFE
 /
h-./ eV, XhHbggll8T277;K;KH;UVWXr8   r:   )Nr   )NNr   ) r   rp   rn   collections.abcr   
contextlibr   pathlibr   typingr   r   r   rJ   r|   r
   utilsr   r   r   rx   r2   r   rD   r\   rw   rZ   r   rP   r3   r5   r6   r<   r8   r/   <module>r      sq   	   $ %  ' '   C C NIR 	;8{ ;8|3sDy) 3# 3%PTUXZ]U]P^`deh`iPiJj 33%T	* 3# 3C 3D 33PuS$Y/ 3Px} 3PPT 3PlUeCI. Uhsm UTW Ufj U6 jo!X
T	
!X"*3-!X?GS	?R!Xcf!X	!Xr8   