U
    ­Ê¹j{'  ã                   @   s¤   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	 d dl
mZ ddlmZmZ ddlmZ ddd	d
ddgZdddddddœZdddddddœZG dd„ deƒZdS )é    N)ÚAnyÚCallableÚDictÚListÚOptionalÚTupleÚUnion)ÚImageé   )Údownload_and_extract_archiveÚverify_str_arg)ÚVisionDatasetZkingdomZphylumÚclassÚorderÚfamilyZgenuszRhttps://ml-inat-competition-datasets.s3.amazonaws.com/2017/train_val_images.tar.gzzOhttps://ml-inat-competition-datasets.s3.amazonaws.com/2018/train_val2018.tar.gzzOhttps://ml-inat-competition-datasets.s3.amazonaws.com/2019/train_val2019.tar.gzzGhttps://ml-inat-competition-datasets.s3.amazonaws.com/2021/train.tar.gzzLhttps://ml-inat-competition-datasets.s3.amazonaws.com/2021/train_mini.tar.gzzEhttps://ml-inat-competition-datasets.s3.amazonaws.com/2021/val.tar.gz)Ú2017Z2018Z2019Ú
2021_trainZ2021_train_miniZ
2021_validZ 7c784ea5e424efaec655bd392f87301fZ b1c6952ce38f31868cc50ea72d066cc3Z c60a6e2962c9b8ccbd458d12c8582644Z e0526d53c7f7b2e3167b2b43bb2690edZ db6ed8330e634445efc8fec83ae81442Z f6f6e0e242e3d4c9569ba56400938afcc                	       s¸   e Zd ZdZdeeeee ef ee ee e	ddœ‡ fdd„Z
dd	œd
d„Zdd	œdd„Zeeeef dœdd„Zed	œdd„Zeeedœdd„Ze	d	œdd„Zdd	œdd„Z‡  ZS )ÚINaturalistaF  `iNaturalist <https://github.com/visipedia/inat_comp>`_ Dataset.

    Args:
        root (string): Root directory of dataset where the image files are stored.
            This class does not require/use annotation files.
        version (string, optional): Which version of the dataset to download/use. One of
            '2017', '2018', '2019', '2021_train', '2021_train_mini', '2021_valid'.
            Default: `2021_train`.
        target_type (string or list, optional): Type of target to use, for 2021 versions, one of:

            - ``full``: the full category (species)
            - ``kingdom``: e.g. "Animalia"
            - ``phylum``: e.g. "Arthropoda"
            - ``class``: e.g. "Insecta"
            - ``order``: e.g. "Coleoptera"
            - ``family``: e.g. "Cleridae"
            - ``genus``: e.g. "Trichodes"

            for 2017-2019 versions, one of:

            - ``full``: the full (numeric) category
            - ``super``: the super category, e.g. "Amphibians"

            Can also be a list to output a tuple with all specified target types.
            Defaults to ``full``.
        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.
        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.
    r   ÚfullNF)ÚrootÚversionÚtarget_typeÚ	transformÚtarget_transformÚdownloadÚreturnc                    s  t |dt ¡ ƒ| _tƒ jtj ||¡||d� tj	|dd� |rH|  
¡  |  ¡ sXtdƒ‚g | _i | _g | _t|tƒsz|g}| jd d… dkr¦dd	„ |D ƒ| _|  ¡  nd
d	„ |D ƒ| _|  ¡  g | _t| jƒD ]8\}}t tj | j|¡¡}	|	D ]}
| j ||
f¡ qðqÎd S )Nr   )r   r   T)Úexist_okzHDataset not found or corrupted. You can use download=True to download ité   Z2021c                 S   s   g | ]}t |d dt˜ƒ‘qS )r   r   )r   )r   ÚCATEGORIES_2021©Ú.0Út© r"   ú_/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torchvision/datasets/inaturalist.pyÚ
<listcomp>a   s     z(INaturalist.__init__.<locals>.<listcomp>c                 S   s   g | ]}t |d dƒ‘qS )r   )r   Úsuper)r   r   r"   r"   r#   r$   d   s     )r   ÚDATASET_URLSÚkeysr   r%   Ú__init__ÚosÚpathÚjoinÚmakedirsr   Ú_check_integrityÚRuntimeErrorÚall_categoriesÚcategories_indexÚcategories_mapÚ
isinstanceÚlistr   Ú
_init_2021Ú_init_pre2021ÚindexÚ	enumerateÚlistdirr   Úappend)Úselfr   r   r   r   r   r   Ú	dir_indexÚdir_nameÚfilesÚfname©Ú	__class__r"   r#   r(   B   s,    	

zINaturalist.__init__)r   c                 C   sø   t t | j¡ƒ| _dd„ tD ƒ| _t| jƒD ]Æ\}}| d¡}t	|ƒdkrZt
d|› d�ƒ‚|d |d›kr„t
d	|d › d
|d›�ƒ‚i }tt|dd… ƒD ]J\}}|| j| krÀ| j| | }nt	| j| ƒ}|| j| |< |||< qš| j |¡ q,dS )zInitialize based on 2021 layoutc                 S   s   i | ]
}|i “qS r"   r"   )r    Úkr"   r"   r#   Ú
<dictcomp>u   s      z*INaturalist._init_2021.<locals>.<dictcomp>Ú_é   zUnexpected category name z, wrong number of piecesr   Z05dzUnexpected category id z, expecting r
   é   N)Úsortedr)   r8   r   r/   r   r0   r7   ÚsplitÚlenr.   Úzipr1   r9   )r:   r;   r<   ÚpiecesZcat_mapÚcatÚnameÚcat_idr"   r"   r#   r4   o   s     

zINaturalist._init_2021c              
   C   sb  di i| _ d}tt | j¡ƒ}t|ƒD �]
\}}|| j d |< tt tj | j|¡¡ƒ}|D ]Ô}| jdkrx|}|d7 }n0zt	|ƒ}W n" t
k
r¦   td|› �ƒ‚Y nX |t| jƒkrôt| jƒ}| j i g|| d  ¡ | j dg|| d  ¡ | j| �rtd|› �ƒ‚d|i| j|< tj ||¡| j|< q\q&t| jƒD ]\}	}
|
�s>td|	› �ƒ‚�q>d	S )
z$Initialize based on 2017-2019 layoutr%   r   r   r
   z!Unexpected non-numeric dir name: Ú zDuplicate category zMissing category N)r0   rF   r)   r8   r   r7   r*   r+   r   ÚintÚ
ValueErrorr.   rH   r1   Úextendr/   )r:   Z	cat_indexZsuper_categoriesZsindexZscatZsubcategoriesZsubcatZsubcat_iZold_lenZcindexÚcr"   r"   r#   r5   ‡   s2    



zINaturalist._init_pre2021)r6   r   c                 C   s°   | j | \}}t tj | j| j| |¡¡}g }| jD ],}|dkrN| 	|¡ q6| 	| j
| | ¡ q6t|ƒdkrxt|ƒn|d }| jdk	r”|  |¡}| jdk	r¨|  |¡}||fS )zž
        Args:
            index (int): Index

        Returns:
            tuple: (image, target) where the type of target specified by target_type.
        r   r
   r   N)r6   r	   Úopenr)   r*   r+   r   r/   r   r9   r1   rH   Útupler   r   )r:   r6   rM   r>   ZimgÚtargetr!   r"   r"   r#   Ú__getitem__ª   s    	




zINaturalist.__getitem__c                 C   s
   t | jƒS )N)rH   r6   ©r:   r"   r"   r#   Ú__len__Æ   s    zINaturalist.__len__)Úcategory_typeÚcategory_idr   c                 C   sn   |dkr| j | S || jkr.td|› d�ƒ‚n<| j|  ¡ D ]\}}||kr<|  S q<td|› d|› �ƒ‚dS )a  
        Args:
            category_type(str): one of "full", "kingdom", "phylum", "class", "order", "family", "genus" or "super"
            category_id(int): an index (class id) from this category

        Returns:
            the name of the category
        r   zInvalid category type 'ú'zInvalid category id z for N)r/   r0   rP   Úitems)r:   rY   rZ   rL   Úidr"   r"   r#   Úcategory_nameÉ   s    	


zINaturalist.category_namec                 C   s"   t j | j¡o tt  | j¡ƒdkS )Nr   )r)   r*   Úexistsr   rH   r8   rW   r"   r"   r#   r-   Ý   s    zINaturalist._check_integrityc                 C   s¬   |   ¡ rtd| j› d�ƒ‚tj | j¡}tt| j || j› d�t	| j d� tj 
|tj t| j ¡ d¡¡}tj |¡sˆtd|› �ƒ‚t || j¡ td| j› d�ƒ d S )	NzThe directory z[ already exists. If you want to re-download or re-extract the images, delete the directory.z.tgz)ÚfilenameÚmd5z.tar.gzz#Unable to find downloaded files at zDataset version 'z*' has been downloaded and prepared for use)r-   r.   r   r)   r*   Údirnamer   r&   r   ÚDATASET_MD5r+   ÚbasenameÚrstripr_   ÚrenameÚprint)r:   Z	base_rootZorig_dir_namer"   r"   r#   r   à   s     ÿ  
 ÿ"zINaturalist.download)r   r   NNF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ústrr   r   r   r   Úboolr(   r4   r5   rO   r   r   rV   rX   r^   r-   r   Ú__classcell__r"   r"   r?   r#   r      s,   %     ùø-#r   )r)   Úos.pathÚtypingr   r   r   r   r   r   r   ZPILr	   Úutilsr   r   Zvisionr   r   r&   rc   r   r"   r"   r"   r#   Ú<module>   s*   $ú
ú
