
    kh2                        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eef   d
ej                  fdZdeeef   d
efdZdeeef   d
efdZ G d de      Zy)    N)Path)AnyCallablecastDictListOptionalTupleUnion)Image   )VisionDatasetfilename
extensions.returnc                 ~    | j                         j                  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   s     W/var/www/teggl/fontify/venv/lib/python3.12/site-packages/torchvision/datasets/folder.pyhas_file_allowed_extensionr      s4     >>$$:j#3NZffTYZdTe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      t	        |      D ci c]  \  }}||
 }}}||fS c c}}w )zWFinds the class folders in a dataset.

    See :class:`DatasetFolder` for details.
    c              3   V   K   | ]!  }|j                         s|j                   # y wN)is_dirname).0entrys     r   	<genexpr>zfind_classes.<locals>.<genexpr>)   s     UEellnUZZUs   ))z"Couldn't find any class folder in .)sortedosscandirFileNotFoundError	enumerate)r   classesicls_nameclass_to_idxs        r   find_classesr1   $   sf    
 URZZ	-BUUG"DYKq QRR3<W3EFKAxHaKFLFL   Gs   Ar0   is_valid_fileallow_emptyc                    t         j                  j                  |       } |t        |       \  }}n|st	        d      du xr |du }duxr |du}|s|rt	        d      dt
        dt        ffd}t        t        t
        gt        f   |      }g }t               }	t        |j                               D ]  }
||
   }t         j                  j                  | |
      }t         j                  j                  |      sHt        t        j                  |d            D ]j  \  }}}t        |      D ]V  }t         j                  j                  ||      } ||      s,||f}|j                  |       |
|	vsF|	j!                  |
       X l  t        |j                               |	z
  }|rV|sTd	d
j                  t        |             d})|dt#        t
              rnd
j                         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   )r5   r   s    r   r2   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
expanduserr1   
ValueErrorr   boolr   r   setr(   keysjoinisdirwalkappendaddr   r+   )r   r0   r   r2   r3   _	both_noneboth_something	instancesavailable_classestarget_classclass_index
target_dirrootfnamesfnamer8   itemempty_classesmsgs     `                 r   make_datasetrQ   1   s    ""9-I&y1<`aad"<}'<It+IT0INNhii	=S 	=T 	= 3%+.>MI|0023 <"<0WW\\)\:
ww}}Z(%bggjd&KL 	<OD!V <ww||D%0 &,D$$T*#+<<)--l;<	<< ))+,/@@M[4TYYvm?T5U4VVXY!/jUX>Y
_c_h_his_t/uvvC$$r   c                   f    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
    NrK   loaderr   .	transformtarget_transformr2   r3   r   c                 &   t         |   |||       | j                  | j                        \  }}	| j	                  | j                  |	|||      }
|| _        || _        || _        |	| _        |
| _	        |
D cg c]  }|d   	 c}| _
        y c c}w )N)rU   rV   )r0   r   r2   r3   r   )super__init__r1   rK   rQ   rT   r   r-   r0   samplestargets)selfrK   rT   r   rU   rV   r2   r3   r-   r0   rZ   s	__class__s               r   rY   zDatasetFolder.__init__   s     	EUV $ 1 1$)) <##II%!'# $ 
 $(&-.!..s   9Br   r0   c                 <    |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)
        z*The class_to_idx parameter cannot be None.)r   r2   r3   )r:   rQ   )r   r0   r   r2   r3   s        r   rQ   zDatasetFolder.make_dataset   s2    @  I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.
        )r1   )r\   r   s     r   r1   zDatasetFolder.find_classes   s    6 I&&r   indexc                     | j                   |   \  }}| j                  |      }| j                  | j                  |      }| j                  | j                  |      }||fS )z
        Args:
            index (int): Index

        Returns:
            tuple: (sample, target) where target is class_index of the target class.
        )rZ   rT   rU   rV   )r\   ra   r8   targetsamples        r   __getitem__zDatasetFolder.__getitem__   sb     ||E*fT">>%^^F+F  ,**62Fv~r   c                 ,    t        | j                        S r!   )lenrZ   )r\   s    r   __len__zDatasetFolder.__len__   s    4<<  r   )NNNNF)NNF)__name__
__module____qualname____doc__r   r   r   r   r   r	   r
   r;   rY   staticmethodr   intr   rQ   r1   re   rh   __classcell__r^   s   @r   rS   rS   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   rS   )	z.jpgz.jpegz.pngz.ppmz.bmpz.pgmz.tifz.tiffz.webpr8   c                     t        | d      5 }t        j                   |      }|j                  d      cd d d        S # 1 sw Y   y xY w)NrbRGB)openr   convert)r8   fimgs      r   
pil_loaderrx     s<    	dD	 "Qjjm{{5!" " "s	   &=Ac                 b    dd l }	 |j                  |       S # t        $ r t        |       cY S w xY w)Nr   )accimager   OSErrorrx   )r8   rz   s     r   accimage_loaderr|     s3     ~~d##  $ s    ..c                 N    ddl m}  |       dk(  rt        |       S t        |       S )Nr   )get_image_backendrz   )torchvisionr~   r|   rx   )r8   r~   s     r   default_loaderr     s&    -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 )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
    NFrK   rU   rV   rT   r2   r3   c           	      d    t         |   |||t        nd ||||       | j                  | _        y )N)rU   rV   r2   r3   )rX   rY   r   rZ   imgs)r\   rK   rU   rV   rT   r2   r3   r^   s          r   rY   zImageFolder.__init__?  s@     	+3N-'# 	 	
 LL	r   )ri   rj   rk   rl   r   r   r   r   r	   r   r   r;   rY   ro   rp   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   rn   r1   rQ   rS   r   rx   r|   r   r    r   r   <module>r      s   	   J J J  !
g 
g%U3PS8_@T:U 
gZ^ 
g	@C 	@D 	@
!E#t), 
!tCy$sCx.7P1Q 
! .28<599S$Y94S>*9 sE#s(O3459 HcUD[12	9
 9 
%S/9xQ!M Q!h ]"U39% "%++ " %T	*  s   sDy)  c  2!- 2!r   