
    kh"                        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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)contextmanager)Path)AnyDictIteratorListOptionalTuple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
            Y/var/www/teggl/fontify/venv/lib/python3.12/site-packages/torchvision/datasets/imagenet.pyr$   zImageNet.__init__3   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    r2   r!   zImageNet.parse_archivesB   sy    rww||DIIyAB +ww}}T../zzW$#DII.u$!$)), % 0    c                 j    t         j                  j                  | j                  | j                        S N)r   r   r4   r   r   r:   s    r2   r%   zImageNet.split_folderL   s    ww||DIItzz22r;   c                 :     dj                   di | j                  S )NzSplit: {split} )format__dict__r:   s    r2   
extra_reprzImageNet.extra_reprP   s    &&&777r;   )r   )r   N)__name__
__module____qualname____doc__r   strr   r   r$   r!   propertyr%   rB   __classcell__)r1   s   @r2   r   r      sd    8`U39- `c `s `W[ `- 3c 3 38C 8r;   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.)	r5   r   r   r4   r   torchloadRuntimeErrorr@   )r   rJ   msgs      r2   r"   r"   T   s\    |77<<d#Dtzz$T22J 	 3::dD122r;   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   r4   rO   r@   )r   rJ   rQ   rP   s       r2   _verify_archiverS   c   sC    277<<d3S9E 	 3::dD122 :r;   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   r4   loadmatlistzipr*   tupler   )rU   metafilemetanums_childrenr.   num_childrenidcsr'   r&   r/   r-   idx_to_wnidr,   sios                r2   parse_meta_matz,parse_devkit_archive.<locals>.parse_meta_matw   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 )NrW   z&ILSVRC2012_validation_ground_truth.txt)r   r   r4   open	readlinesint)rU   rJ   txtfhval_idcsval_idxs        r2   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    r2   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iorG   r
   r   rk   r   r   r   ARCHIVE_METArS   r   r   r   r4   rM   saver5   )r   rJ   rg   ro   rv   archive_metarQ   ru   rU   re   r,   rm   r.   	val_wnidsrf   s                 @r2   r6   r6   l   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)rz   rS   r   r   r4   r   listdirsplitext)r   rJ   r~   r|   rQ   
train_rootarchivearchivess           r2   r8   r8      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   r4   ).0imageval_roots     r2   	<genexpr>z$parse_val_archive.<locals>.<genexpr>   s      TeBGGLL51Ts   *-)rz   r"   rS   r   r   r4   r   sortedr   setmkdirr^   rs   movebasename)
r   rJ   r'   r~   r|   rQ   imagesr-   img_filer   s
            @r2   r9   r9      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r;   r=   )Nr   )NNr   )r   rs   rq   
contextlibr   pathlibr   typingr   r   r   r   r	   r
   r   rM   r~   r   utilsr   r   r   rz   r5   r   rG   r"   rS   r6   r8   r9   r?   r;   r2   <module>r      sq   	   %  D D D   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r;   