o
    h2                     @   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	 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	eef d
ejfddZde	eef d
efddZde	eef d
efd d!ZG d"d# d#eZdS )%    N)Path)AnyCallablecastOptional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   a/home/www/facesmatcher.com/frenv_anti/lib/python3.10/site-packages/torchvision/datasets/folder.pyhas_file_allowed_extension   s   "
r   c                 C   s
   t | tS )zChecks 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|sd
dt
| d} dur|dt tr nd  7 }t||S )zGenerates 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   )r-   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_somethingZ	instancesZavailable_classesZtarget_classZclass_index
target_dirrootfnamesfnamer1   itemZempty_classesmsgr   r.   r   make_dataset1   sJ   


"rC   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
    NFr>   loaderr   .	transformtarget_transformr+   r,   r   c                    sj   t  j|||d | | j\}}	| j| j|	|||d}
|| _|| _|| _|	| _|
| _	dd |
D | _
d S )N)rF   rG   )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*   r>   rC   rE   r   r(   r)   samplestargets)selfr>   rE   r   rF   rG   r+   r,   r(   r)   rL   	__class__r   r   rK      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,   )r3   rC   )r   r)   r   r+   r,   r   r   r   rC      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*   )rN   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)rL   rE   rF   rG   )rN   rQ   r1   targetsampler   r   r   __getitem__   s   




zDatasetFolder.__getitem__c                 C   s
   t | jS r   )lenrL   )rN   r   r   r   __len__   r/   zDatasetFolder.__len__)NNNNF)NNF)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r4   rK   staticmethoddictintlistrC   r*   rT   rV   __classcell__r   r   rO   r   rD   m   sX     
	

.(rD   )	z.jpgz.jpegz.pngz.ppmz.bmpz.pgmz.tifz.tiffz.webpr1   c                 C   sB   t | d}t |}|dW  d    S 1 sw   Y  d S )NrbRGB)openr   convert)r1   fZimgr   r   r   
pil_loader  s   
$re   c                 C   s0   dd l }z|| W S  ty   t|  Y S w )Nr   )accimager   OSErrorre   )r1   rf   r   r   r   accimage_loader  s   rh   c                 C   s&   ddl m} | dkrt| S t| S )Nr   )get_image_backendrf   )Ztorchvisionri   rh   re   )r1   ri   r   r   r   default_loader  s   
rj   c                       sn   e Zd ZdZddeddfdeeef 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 )ImageFoldera  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 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.
        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
    NFr>   rF   rG   rE   r+   r,   c              	      s2   t  j|||d u rtnd ||||d | j| _d S )N)rF   rG   r+   r,   )rJ   rK   r   rL   Zimgs)rN   r>   rF   rG   rE   r+   r,   rO   r   r   rK   ?  s   		zImageFolder.__init__)rW   rX   rY   rZ   rj   r   r   r   r   r   r   r4   rK   r_   r   r   rO   r   rk     s(    "
rk   )NNNF)r$   Zos.pathpathlibr   typingr   r   r   r   r   ZPILr   Zvisionr
   r   r   r4   r   r   r^   r\   r]   r*   rC   rD   r   re   rh   rj   rk   r   r   r   r   <module>   sB    &.

< 
	