o
    ôjj2  ã                   @   s�  d dl Z d dlZ d dlmZ d dlmZmZmZmZm	Z	m
Z
mZmZ d dlmZ ddlmZ dedeeeed	f f d
efdd„Zded
efdd„Zdeeef d
ee	e eeef f fdd„Z				d$deeef de
eeef  de
eeeed	f f  de
eegef  ded
e	eeef  fdd„ZG dd„ deƒZdZded
ejfdd„Zded
efdd„Zded
efd d!„ZG d"d#„ d#eƒZdS )%é    N)ÚPath)ÚAnyÚCallableÚcastÚDictÚListÚOptionalÚTupleÚUnion)ÚImageé   )ÚVisionDatasetÚfilenameÚ
extensions.Úreturnc                 C   s"   |   ¡  t|tƒr|¡S t|ƒ¡S )a   Checks if a file is an allowed extension.

    Args:
        filename (string): path to a file
        extensions (tuple of strings): extensions to consider (lowercase)

    Returns:
        bool: True if the filename ends with one of given extensions
    )ÚlowerÚendswithÚ
isinstanceÚstrÚtuple)r   r   © r   úl/var/www/html/academy/tools/voices/clone/sv-venv/lib/python3.10/site-packages/torchvision/datasets/folder.pyÚhas_file_allowed_extension   s   "
r   c                 C   s
   t | tƒS )z¼Checks if a file is an allowed image extension.

    Args:
        filename (string): path to a file

    Returns:
        bool: True if the filename ends with a known image extension
    )r   ÚIMG_EXTENSIONS)r   r   r   r   Úis_image_file   s   
	r   Ú	directoryc                 C   sF   t dd„ t | ¡D ƒƒ}|std| › d�ƒ‚dd„ t|ƒD ƒ}||fS )zWFinds the class folders in a dataset.

    See :class:`DatasetFolder` for details.
    c                 s   s   � | ]
}|  ¡ r|jV  qd S ©N)Úis_dirÚname)Ú.0Úentryr   r   r   Ú	<genexpr>)   s   € zfind_classes.<locals>.<genexpr>z"Couldn't find any class folder in Ú.c                 S   s   i | ]\}}||“qS r   r   )r   ÚiÚcls_namer   r   r   Ú
<dictcomp>-   s    z find_classes.<locals>.<dictcomp>)ÚsortedÚosÚscandirÚFileNotFoundErrorÚ	enumerate)r   ÚclassesÚclass_to_idxr   r   r   Úfind_classes$   s
   r-   Fr,   Úis_valid_fileÚallow_emptyc                    sš  t j | ¡} |du rt| ƒ\}}n|stdƒ‚ˆ du o|du }ˆ duo&|du}|s+|r/tdƒ‚ˆ dur>dtdtf‡ fdd„}tttgtf |ƒ}g }t	ƒ }	t
| ¡ ƒD ]G}
||
 }t j | |
¡}t j |¡sgqSt
t j|dd	�ƒD ])\}}}t
|ƒD ]}t j ||¡}||ƒr˜||f}| |¡ |
|	vr˜|	 |
¡ qyqpqSt	| ¡ ƒ|	 }|rË|sËd
d t
|ƒ¡› d�}ˆ durÇ|dtˆ tƒr¿ˆ nd ˆ ¡› �7 }t|ƒ‚|S )zïGenerates a list of samples of a form (path_to_sample, class).

    See :class:`DatasetFolder` for details.

    Note: The class_to_idx parameter is here optional and will use the logic of the ``find_classes`` function
    by default.
    NzE'class_to_index' must have at least one entry to collect any samples.zMBoth extensions and is_valid_file cannot be None or not None at the same timeÚxr   c                    s
   t | ˆ ƒS r   )r   )r0   ©r   r   r   r.   M   ó   
z#make_dataset.<locals>.is_valid_fileT)Úfollowlinksz$Found no valid file for the classes z, z. zSupported extensions are: )r'   ÚpathÚ
expanduserr-   Ú
ValueErrorr   Úboolr   r   Úsetr&   ÚkeysÚjoinÚisdirÚwalkÚappendÚaddr   r)   )r   r,   r   r.   r/   Ú_Z	both_noneZboth_somethingÚ	instancesZavailable_classesÚtarget_classZclass_indexÚ
target_dirÚrootÚfnamesÚfnamer4   ÚitemZempty_classesÚmsgr   r1   r   Úmake_dataset1   sJ   

€ùÿ
"rH   c                       s<  e Zd ZdZ					ddeeef deegef de	e
edf  de	e d	e	e d
e	eegef  deddf‡ fdd„Ze			ddeeef deeef de	e
edf  d
e	eegef  dedee
eef  fdd„ƒZdeeef de
ee eeef f fdd„Zdede
eef fdd„Zdefdd„Z‡  ZS )ÚDatasetFolderaŒ  A generic data loader.

    This default directory structure can be customized by overriding the
    :meth:`find_classes` method.

    Args:
        root (str or ``pathlib.Path``): Root directory path.
        loader (callable): A function to load a sample given its path.
        extensions (tuple[string]): A list of allowed extensions.
            both extensions and is_valid_file should not be passed.
        transform (callable, optional): A function/transform that takes in
            a sample and returns a transformed version.
            E.g, ``transforms.RandomCrop`` for images.
        target_transform (callable, optional): A function/transform that takes
            in the target and transforms it.
        is_valid_file (callable, optional): A function that takes path of a file
            and check if the file is a valid file (used to check of corrupt files)
            both extensions and is_valid_file should not be passed.
        allow_empty(bool, optional): If True, empty folders are considered to be valid classes.
            An error is raised on empty folders if False (default).

     Attributes:
        classes (list): List of the class names sorted alphabetically.
        class_to_idx (dict): Dict with items (class_name, class_index).
        samples (list): List of (sample path, class_index) tuples
        targets (list): The class_index value for each image in the dataset
    NFrC   Úloaderr   .Ú	transformÚtarget_transformr.   r/   r   c                    sj   t ƒ j|||d� |  | j¡\}}	| j| j|	|||d�}
|| _|| _|| _|	| _|
| _	dd„ |
D ƒ| _
d S )N)rK   rL   )r,   r   r.   r/   c                 S   s   g | ]}|d  ‘qS )r   r   )r   Úsr   r   r   Ú
<listcomp>¤   s    z*DatasetFolder.__init__.<locals>.<listcomp>)ÚsuperÚ__init__r-   rC   rH   rJ   r   r+   r,   ÚsamplesÚtargets)ÚselfrC   rJ   r   rK   rL   r.   r/   r+   r,   rQ   ©Ú	__class__r   r   rP   Š   s   
ûzDatasetFolder.__init__r   r,   c                 C   s"   |du rt dƒ‚t| ||||d�S )a  Generates a list of samples of a form (path_to_sample, class).

        This can be overridden to e.g. read files from a compressed zip file instead of from the disk.

        Args:
            directory (str): root dataset directory, corresponding to ``self.root``.
            class_to_idx (Dict[str, int]): Dictionary mapping class name to class index.
            extensions (optional): A list of allowed extensions.
                Either extensions or is_valid_file should be passed. Defaults to None.
            is_valid_file (optional): A function that takes path of a file
                and checks if the file is a valid file
                (used to check of corrupt files) both extensions and
                is_valid_file should not be passed. Defaults to None.
            allow_empty(bool, optional): If True, empty folders are considered to be valid classes.
                An error is raised on empty folders if False (default).

        Raises:
            ValueError: In case ``class_to_idx`` is empty.
            ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None.
            FileNotFoundError: In case no valid file was found for any class.

        Returns:
            List[Tuple[str, int]]: samples of a form (path_to_sample, class)
        Nz*The class_to_idx parameter cannot be None.)r   r.   r/   )r6   rH   )r   r,   r   r.   r/   r   r   r   rH   ¦   s
    
ÿzDatasetFolder.make_datasetc                 C   s   t |ƒS )ut  Find the class folders in a dataset structured as follows::

            directory/
            â”œâ”€â”€ class_x
            â”‚   â”œâ”€â”€ xxx.ext
            â”‚   â”œâ”€â”€ xxy.ext
            â”‚   â””â”€â”€ ...
            â”‚       â””â”€â”€ xxz.ext
            â””â”€â”€ class_y
                â”œâ”€â”€ 123.ext
                â”œâ”€â”€ nsdf3.ext
                â””â”€â”€ ...
                â””â”€â”€ asd932_.ext

        This method can be overridden to only consider
        a subset of classes, or to adapt to a different dataset directory structure.

        Args:
            directory(str): Root directory path, corresponding to ``self.root``

        Raises:
            FileNotFoundError: If ``dir`` has no class folders.

        Returns:
            (Tuple[List[str], Dict[str, int]]): List of all classes and dictionary mapping each class to an index.
        )r-   )rS   r   r   r   r   r-   Ï   s   zDatasetFolder.find_classesÚindexc                 C   sH   | j | \}}|  |¡}| jdur|  |¡}| jdur |  |¡}||fS )z�
        Args:
            index (int): Index

        Returns:
            tuple: (sample, target) where target is class_index of the target class.
        N)rQ   rJ   rK   rL   )rS   rV   r4   ÚtargetÚsampler   r   r   Ú__getitem__ì   s   




zDatasetFolder.__getitem__c                 C   s
   t | jƒS r   )ÚlenrQ   )rS   r   r   r   Ú__len__ý   r2   zDatasetFolder.__len__)NNNNF)NNF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r
   r   r   r   r   r   r	   r7   rP   Ústaticmethodr   Úintr   rH   r-   rY   r[   Ú__classcell__r   r   rT   r   rI   m   sX     ø
þýüûúùø	÷û
ÿ
þýüûú.(rI   )	z.jpgz.jpegz.pngz.ppmz.bmpz.pgmz.tifz.tiffz.webpr4   c                 C   sB   t | dƒ�}t  |¡}| d¡W  d   ƒ S 1 sw   Y  d S )NÚrbÚRGB)Úopenr   Úconvert)r4   ÚfÚimgr   r   r   Ú
pil_loader  s   
$þri   c                 C   s0   dd l }z| | ¡W S  ty   t| ƒ Y S w )Nr   )Úaccimager   ÚOSErrorri   )r4   rj   r   r   r   Úaccimage_loader  s   þrl   c                 C   s&   ddl m} |ƒ dkrt| ƒS t| ƒS )Nr   )Úget_image_backendrj   )Útorchvisionrm   rl   ri   )r4   rm   r   r   r   Údefault_loader  s   
ro   c                       sf   e Zd ZdZddeddfdedee dee deegef deeege	f  d	e	f‡ fd
d„Z
‡  ZS )ÚImageFolderat  A generic data loader where the images are arranged in this way by default: ::

        root/dog/xxx.png
        root/dog/xxy.png
        root/dog/[...]/xxz.png

        root/cat/123.png
        root/cat/nsdf3.png
        root/cat/[...]/asd932_.png

    This class inherits from :class:`~torchvision.datasets.DatasetFolder` so
    the same methods can be overridden to customize the dataset.

    Args:
        root (str or ``pathlib.Path``): Root directory path.
        transform (callable, optional): A function/transform that takes in a 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.
        loader (callable, optional): A function to load an image given its path.
        is_valid_file (callable, optional): A function that takes path of an Image file
            and check if the file is a valid file (used to check of corrupt files)
        allow_empty(bool, optional): If True, empty folders are considered to be valid classes.
            An error is raised on empty folders if False (default).

     Attributes:
        classes (list): List of the class names sorted alphabetically.
        class_to_idx (dict): Dict with items (class_name, class_index).
        imgs (list): List of (image path, class_index) tuples
    NFrC   rK   rL   rJ   r.   r/   c              	      s2   t ƒ j|||d u rtnd ||||d� | j| _d S )N)rK   rL   r.   r/   )rO   rP   r   rQ   Úimgs)rS   rC   rK   rL   rJ   r.   r/   rT   r   r   rP   ?  s   	ù	zImageFolder.__init__)r\   r]   r^   r_   ro   r   r   r   r   r7   rP   rb   r   r   rT   r   rp     s(    "ùþýüûúùrp   )NNNF)r'   Úos.pathÚpathlibr   Útypingr   r   r   r   r   r   r	   r
   ÚPILr   Úvisionr   r   r7   r   r   ra   r-   rH   rI   r   ri   rl   ro   rp   r   r   r   r   Ú<module>   sB    (&.û
ÿþýüû
ú< 
	