
    ڧgw2                     $   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Zded
efdZdeeef         d
ee	e         eeef         f         f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Z G d de          ZdZded
ej        fdZded
efdZded
efdZ G d de          ZdS )    N)Path)AnyCallablecastDictListOptionalTupleUnion)Image   )VisionDatasetfilename
extensions.returnc                     |                                                      t          |t                    r|n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   s     W/var/www/html/ai-engine/env/lib/python3.11/site-packages/torchvision/datasets/folder.pyhas_file_allowed_extensionr      s?     >>$$:j#3N3N%eZZTYZdTeTefff    c                 ,    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   s    r   is_image_filer      s     &h???r   	directoryc                     t          d t          j        |           D                       }|st          d|  d          d t	          |          D             }||fS )zWFinds the class folders in a dataset.

    See :class:`DatasetFolder` for details.
    c              3   L   K   | ]}|                                 |j        V   d S N)is_dirname).0entrys     r   	<genexpr>zfind_classes.<locals>.<genexpr>)   s1      UUEellnnUUZUUUUUUr   z"Couldn't find any class folder in .c                     i | ]\  }}||	S  r)   )r$   icls_names      r   
<dictcomp>z find_classes.<locals>.<dictcomp>-   s    FFFKAxHaFFFr   )sortedosscandirFileNotFoundError	enumerate)r   classesclass_to_idxs      r   find_classesr4   $   ss    
 UURZ	-B-BUUUUUG S QY Q Q QRRRFF9W3E3EFFFLL  r   Fr3   is_valid_fileallow_emptyc                    t           j                            |           } |t          |           \  }}n|st	          d          du o|du }duo|du}|s|rt	          d          dt
          dt          ffd}t          t          t
          gt          f         |          }g }t                      }	t          |                                          D ]}
||
         }t           j                            | |
          }t           j                            |          sJt          t          j        |d                    D ]u\  }}}t          |          D ]_}t           j                            ||          } ||          r2||f}|                    |           |
|	vr|	                    |
           `vt          |                                          |	z
  }|rk|sid	d
                    t          |                     d}2|dt#          t
                    rnd
                               z  }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                 $    t          |           S r!   )r   )r8   r   s    r   r5   z#make_dataset.<locals>.is_valid_fileM   s    -a<<<r   T)followlinksz$Found no valid file for the classes z, z. zSupported extensions are: )r.   path
expanduserr4   
ValueErrorr   boolr   r   setr-   keysjoinisdirwalkappendaddr   r0   )r   r3   r   r5   r6   _	both_noneboth_something	instancesavailable_classestarget_classclass_index
target_dirrootfnamesfnamer;   itemempty_classesmsgs     `                 r   make_datasetrT   1   s    ""9--I&y11<< b`aaad"<}'<It+IT0IN jN jhiii	=S 	=T 	= 	= 	= 	= 	= 	= 3%+.>>MI|002233 < <"<0W\\)\::
w}}Z(( 	%bgjd&K&K&KLL 	< 	<OD!V < <w||D%00 =&& <,D$$T***#+<<<)--l;;;<	< ))++,,/@@M %[ %YTYYvm?T?T5U5UYYY!vjUX>Y>Y0t

_c_h_his_t_tvvvC$$$r   c                       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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            Zdeeef         de
ee         eeef         f         fdZdede
eef         fdZdefdZ x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
    NFrN   loaderr   .	transformtarget_transformr5   r6   r   c                 0   t                                          |||           |                     | j                  \  }}	|                     | j        |	|||          }
|| _        || _        || _        |	| _        |
| _	        d |
D             | _
        d S )N)rX   rY   )r3   r   r5   r6   c                     g | ]
}|d          S )r   r)   )r$   ss     r   
<listcomp>z*DatasetFolder.__init__.<locals>.<listcomp>   s    ...!...r   )super__init__r4   rN   rT   rW   r   r2   r3   samplestargets)selfrN   rW   r   rX   rY   r5   r6   r2   r3   r`   	__class__s              r   r_   zDatasetFolder.__init__   s     	EUVVV $ 1 1$) < <##I%!'# $ 
 
 $(..g...r   r   r3   c                 L    |t          d          t          | ||||          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   r5   r6   )r=   rT   )r   r3   r   r5   r6   s        r   rT   zDatasetFolder.make_dataset   s?    @  IJJJ|
-ep
 
 
 	
r   c                      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.
        )r4   )rb   r   s     r   r4   zDatasetFolder.find_classes   s    6 I&&&r   indexc                     | j         |         \  }}|                     |          }| j        |                     |          }| j        |                     |          }||fS )z
        Args:
            index (int): Index

        Returns:
            tuple: (sample, target) where target is class_index of the target class.
        )r`   rW   rX   rY   )rb   rf   r;   targetsamples        r   __getitem__zDatasetFolder.__getitem__   sd     |E*fT"">%^^F++F ,**622Fv~r   c                 *    t          | j                  S r!   )lenr`   )rb   s    r   __len__zDatasetFolder.__len__   s    4<   r   )NNNNF)NNF)__name__
__module____qualname____doc__r   r   r   r   r   r	   r
   r>   r_   staticmethodr   intr   rT   r4   rj   rm   __classcell__rc   s   @r   rV   rV   m   s        @ 15(,/39=!/ /CI/ #$/ U38_-	/
 H%/ #8,/  # 56/ / 
/ / / / / /8  159=!&
 &
d#&
38n&
 U38_-&
  # 56	&

 &
 
eCHo	&
 &
 &
 \&
P'eCI&6 '5cDQTVYQYNAZ;[ ' ' ' ': sCx    "! ! ! ! ! ! ! ! !r   rV   )	z.jpgz.jpegz.pngz.ppmz.bmpz.pgmz.tifz.tiffz.webpr;   c                     t          | d          5 }t          j         |          }|                    d          cd d d            S # 1 swxY w Y   d S )NrbRGB)openr   convert)r;   fimgs      r   
pil_loaderr}     s    	dD		 "Qjmm{{5!!" " " " " " " " " " " " " " " " " "s   )AAAc                 t    dd l }	 |                    |           S # t          $ r t          |           cY S w xY w)Nr   )accimager   OSErrorr}   )r;   r   s     r   accimage_loaderr     sQ    OOO ~~d###      $ s    77c                 f    ddl m}  |            dk    rt          |           S t          |           S )Nr   )get_image_backendr   )torchvisionr   r   r}   )r;   r   s     r   default_loaderr     sD    ------j((t$$$$r   c                        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
Z x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
    NFrN   rX   rY   rW   r5   r6   c           	          t                                          |||t          nd ||||           | j        | _        d S )N)rX   rY   r5   r6   )r^   r_   r   r`   imgs)rb   rN   rX   rY   rW   r5   r6   rc   s          r   r_   zImageFolder.__init__?  sS     	+3NN-'# 	 	
 	
 	
 L			r   )rn   ro   rp   rq   r   r   r   r   r	   r   r   r>   r_   rt   ru   s   @r   r   r     s         D )-/3'59=!! !CI! H%! #8,	!
 #$!  # 56! ! ! ! ! ! ! ! ! ! !r   r   )NNNF)r.   os.pathpathlibr   typingr   r   r   r   r   r	   r
   r   PILr   visionr   r   r>   r   r   rs   r4   rT   rV   r   r}   r   r   r   r)   r   r   <module>r      s   				        J J J J J J J J J J J J J J J J J J J J       ! ! ! ! ! !
g 
g%U3PS8_@T:U 
gZ^ 
g 
g 
g 
g	@C 	@D 	@ 	@ 	@ 	@
!E#t), 
!tCy$sCx.7P1Q 
! 
! 
! 
! .28<599 9S$Y94S>*9 sE#s(O3459 HcUD[12	9
 9 
%S/9 9 9 9xQ! Q! Q! Q! Q!M Q! Q! Q!h ]"S "U[ " " " " #  #                   2! 2! 2! 2! 2!- 2! 2! 2! 2! 2!r   