Ë
    –\;jãC  ã                   óŒ   — d dl Z d dlmZ d dlZd dlmZ d dlmZ g Zd„ Z	dd„Z
 G d„ de«      Zd	Zd
„ Zd„ Zd„ Z G d„ de«      Zy)é    N)ÚImage)ÚDataset)Ú
try_importc                 óÒ   — t        |t        t        f«      sJ d«       ‚t        |D �cg c]  }|j                  «       ‘Œ c}«      }| j                  «       j	                  |«      S c c}w )zòChecks if a file is a valid extension.

    Args:
        filename (str): path to a file
        extensions (list[str]|tuple[str]): extensions to consider

    Returns:
        bool: True if the filename ends with one of given extensions
    z#`extensions` must be list or tuple.)Ú
isinstanceÚlistÚtupleÚlowerÚendswith)ÚfilenameÚ
extensionsÚxs      úfG:\00. PROJECTS\API\Inventory\templateJSON\kerjaOCR\Lib\site-packages\paddle/vision/datasets/folder.pyÚhas_valid_extensionr      se   € ô Ø”Tœ5�Môð -à,ó-ð ô ©:Ó6©: a˜Ÿ™�	¨:Ñ6Ó7€JØ�>‰>Ó×$Ñ$ ZÓ0Ð0ùò 7s   §A$c                 ó  ‡— g }t         j                  j                  | «      } ‰�ˆfd„}t        |j	                  «       «      D ]¼  }t         j                  j                  | |«      }t         j                  j                  |«      sŒCt        t        j                  |d¬«      «      D ]W  \  }}}	t        |	«      D ]C  }
t         j                  j                  ||
«      } ||«      sŒ,|||   f}|j                  |«       ŒE ŒY Œ¾ |S )Nc                 ó   •— t        | ‰«      S ©N©r   ©r   r   s    €r   Úis_valid_filez#make_dataset.<locals>.is_valid_file1   s   ø€ Ü& q¨*Ó5Ð5ó    T©Úfollowlinks)	ÚosÚpathÚ
expanduserÚsortedÚkeysÚjoinÚisdirÚwalkÚappend)ÚdirÚclass_to_idxr   r   ÚimagesÚtargetÚdÚrootÚ_ÚfnamesÚfnamer   Úitems     `          r   Úmake_datasetr-   +   sÕ   ø€ Ø€FÜ
�'‰'×
Ñ
˜SÓ
!€CàÐô	6ô ˜×*Ñ*Ó,Ö-ˆÜ�G‰G�L‰L˜˜fÓ%ˆÜ�w‰w�}‰}˜QÔØÜ%¤b§g¡g¨a¸TÔ&BÖC‰OˆD�!�VÜ ž�Ü—w‘w—|‘| D¨%Ó0�Ù  Õ&Ø  ,¨vÑ"6Ð7�DØ—M‘M $Õ'ñ	 (ñ  Dð	 .ð €Mr   c                   ó2   — e Zd ZdZ	 	 	 	 dd„Zd„ Zd„ Zd„ Zy)ÚDatasetFoldera  A generic data loader where the samples are arranged in this way:

    .. code-block:: text

        root/class_a/1.ext
        root/class_a/2.ext
        root/class_a/3.ext

        root/class_b/123.ext
        root/class_b/456.ext
        root/class_b/789.ext

    Args:
        root (str): Root directory path.
        loader (Callable, optional): A function to load a sample given its path. Default: None.
        extensions (list[str]|tuple[str], optional): A list of allowed extensions.
            Both :attr:`extensions` and :attr:`is_valid_file` should not be passed.
            If this value is not set, the default is to use ('.jpg', '.jpeg', '.png',
            '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'). Default: None.
        transform (Callable, optional): A function/transform that takes in
            a sample and returns a transformed version. Default: None.
        is_valid_file (Callable, optional): A function that takes path of a file
            and check if the file is a valid file. Both :attr:`extensions` and
            :attr:`is_valid_file` should not be passed. Default: None.

    Returns:
        :ref:`api_paddle_io_Dataset`. An instance of DatasetFolder.

    Attributes:
        classes (list[str]): List of the class names.
        class_to_idx (dict[str, int]): Dict with items (class_name, class_index).
        samples (list[tuple[str, int]]): List of (sample_path, class_index) tuples.
        targets (list[int]): The class_index value for each image in the dataset.

    Example:

        .. code-block:: python

            >>> import shutil
            >>> import tempfile
            >>> import cv2
            >>> import numpy as np
            >>> import paddle.vision.transforms as T
            >>> from pathlib import Path
            >>> from paddle.vision.datasets import DatasetFolder


            >>> def make_fake_file(img_path: str):
            ...     if img_path.endswith((".jpg", ".png", ".jpeg")):
            ...         fake_img = np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8)
            ...         cv2.imwrite(img_path, fake_img)
            ...     elif img_path.endswith(".txt"):
            ...         with open(img_path, "w") as f:
            ...             f.write("This is a fake file.")

            >>> def make_directory(root, directory_hierarchy, file_maker=make_fake_file):
            ...     root = Path(root)
            ...     root.mkdir(parents=True, exist_ok=True)
            ...     for subpath in directory_hierarchy:
            ...         if isinstance(subpath, str):
            ...             filepath = root / subpath
            ...             file_maker(str(filepath))
            ...         else:
            ...             dirname = list(subpath.keys())[0]
            ...             make_directory(root / dirname, subpath[dirname])

            >>> directory_hirerarchy = [
            ...     {"class_0": [
            ...         "abc.jpg",
            ...         "def.png"]},
            ...     {"class_1": [
            ...         "ghi.jpeg",
            ...         "jkl.png",
            ...         {"mno": [
            ...             "pqr.jpeg",
            ...             "stu.jpg"]}]},
            ...     "this_will_be_ignored.txt",
            ... ]

            >>> # You can replace this with any directory to explore the structure
            >>> # of generated data. e.g. fake_data_dir = "./temp_dir"
            >>> fake_data_dir = tempfile.mkdtemp()
            >>> make_directory(fake_data_dir, directory_hirerarchy)
            >>> data_folder_1 = DatasetFolder(fake_data_dir)
            >>> print(data_folder_1.classes)
            ['class_0', 'class_1']
            >>> print(data_folder_1.class_to_idx)
            {'class_0': 0, 'class_1': 1}
            >>> print(data_folder_1.samples)
            >>> # doctest: +SKIP(it's different with windows)
            [('./temp_dir/class_0/abc.jpg', 0), ('./temp_dir/class_0/def.png', 0),
             ('./temp_dir/class_1/ghi.jpeg', 1), ('./temp_dir/class_1/jkl.png', 1),
             ('./temp_dir/class_1/mno/pqr.jpeg', 1), ('./temp_dir/class_1/mno/stu.jpg', 1)]
            >>> # doctest: -SKIP
            >>> print(data_folder_1.targets)
            [0, 0, 1, 1, 1, 1]
            >>> print(len(data_folder_1))
            6

            >>> for i in range(len(data_folder_1)):
            ...     img, label = data_folder_1[i]
            ...     # do something with img and label
            ...     print(type(img), img.size, label)
            ...     # <class 'PIL.Image.Image'> (32, 32) 0


            >>> transform = T.Compose(
            ...     [
            ...         T.Resize(64),
            ...         T.ToTensor(),
            ...         T.Normalize(
            ...             mean=[0.5, 0.5, 0.5],
            ...             std=[0.5, 0.5, 0.5],
            ...             to_rgb=True,
            ...         ),
            ...     ]
            ... )

            >>> data_folder_2 = DatasetFolder(
            ...     fake_data_dir,
            ...     loader=lambda x: cv2.imread(x),  # load image with OpenCV
            ...     extensions=(".jpg",),  # only load *.jpg files
            ...     transform=transform,  # apply transform to every image
            ... )

            >>> print([img_path for img_path, label in data_folder_2.samples])
            >>> # doctest: +SKIP(it's different with windows)
            ['./temp_dir/class_0/abc.jpg', './temp_dir/class_1/mno/stu.jpg']
            >>> # doctest: -SKIP
            >>> print(len(data_folder_2))
            2

            >>> for img, label in iter(data_folder_2):
            ...     # do something with img and label
            ...     print(type(img), img.shape, label)
            ...     # <class 'paddle.Tensor'> [3, 64, 64] 0

            >>> shutil.rmtree(fake_data_dir)
    Nc                 óÔ  — || _         || _        |€t        }| j                  | j                   «      \  }}t	        | j                   |||«      }t        |«      dk(  r-t        d| j                   z   dz   dj                  |«      z   «      ‚|€t        n|| _	        || _
        || _        || _        || _        |D �	cg c]  }	|	d   ‘Œ	 c}	| _        t        j                   «       | _        y c c}	w )Nr   z&Found 0 directories in subfolders of: ú
Supported extensions are: Ú,é   )r(   Ú	transformÚIMG_EXTENSIONSÚ_find_classesr-   ÚlenÚRuntimeErrorr   Údefault_loaderÚloaderr   Úclassesr$   ÚsamplesÚtargetsÚpaddleÚget_default_dtypeÚdtype)
Úselfr(   r:   r   r4   r   r;   r$   r<   Úss
             r   Ú__init__zDatasetFolder.__init__Ï   sì   € ð ˆŒ	Ø"ˆŒØÐÜ'ˆJØ $× 2Ñ 2°4·9±9Ó =Ñˆ�ÜØ�I‰I�| Z°ó
ˆô ˆw‹<˜1ÒäØ<¸t¿y¹yÑHð L1ñ 1Ø36·8±8¸JÓ3GñHóðð )/¨•n¸FˆŒØ$ˆŒàˆŒØ(ˆÔØˆŒÙ&-Ó.¡g ˜˜!› gÑ.ˆŒä×-Ñ-Ó/ˆ�
ùò /s   Â7C%c                 ó  — t        j                  |«      D �cg c]  }|j                  «       sŒ|j                  ‘Œ! }}|j	                  «        t        t        |«      «      D �ci c]  }||   |“Œ
 }}||fS c c}w c c}w )a  
        Finds the class folders in a dataset.

        Args:
            dir (string): Root directory path.

        Returns:
            tuple: (classes, class_to_idx) where classes are relative to (dir),
                    and class_to_idx is a dictionary.

        )r   ÚscandirÚis_dirÚnameÚsortÚranger7   )rA   r#   r'   r;   Úir$   s         r   r6   zDatasetFolder._find_classesñ   sp   € ô $&§:¡:¨c¤?ÓA¡?˜a°a·h±hµj�1—6“6 ?ˆÐAØ�‰ŒÜ/4´S¸³\Ô/BÓCÑ/B¨!˜ ™
 A™Ð/BˆÐCØ˜Ð$Ð$ùò BùâCs   ˜A7®A7Á$A<c                 óŠ   — | j                   |   \  }}| j                  |«      }| j                  �| j                  |«      }||fS )z�
        Args:
            index (int): Index

        Returns:
            tuple: (sample, target) where target is class_index of the target class.
        ©r<   r:   r4   )rA   Úindexr   r&   Úsamples        r   Ú__getitem__zDatasetFolder.__getitem__  sF   € ð —|‘| EÑ*‰ˆˆfØ—‘˜TÓ"ˆØ�>‰>Ð%Ø—^‘^ FÓ+ˆFà�vˆ~Ðr   c                 ó,   — t        | j                  «      S r   ©r7   r<   ©rA   s    r   Ú__len__zDatasetFolder.__len__  ó   € Ü�4—<‘<Ó Ð r   ©NNNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rC   r6   rO   rS   © r   r   r/   r/   B   s,   „ ñJð^ ØØØó 0òD%ò"ó!r   r/   )	z.jpgz.jpegz.pngz.ppmz.bmpz.pgmz.tifz.tiffz.webpc                 ó’   — 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)r   ÚfÚimgs      r   Ú
pil_loaderrb   "  s3   € Ü	ˆd�DÔ	˜QÜ�j‰j˜‹mˆØ�{‰{˜5Ó!÷ 
×	Ò	ús	   �&=½Ac                 ón   — t        d«      }|j                  |j                  | «      |j                  «      S )NÚcv2)r   ÚcvtColorÚimreadÚCOLOR_BGR2RGB)r   rd   s     r   Ú
cv2_loaderrh   (  s,   € Ü
�UÓ
€CØ�<‰<˜Ÿ
™
 4Ó(¨#×*;Ñ*;Ó<Ð<r   c                 óN   — ddl m}  |«       dk(  rt        | «      S t        | «      S )Nr   )Úget_image_backendrd   )Úpaddle.visionrj   rh   rb   )r   rj   s     r   r9   r9   -  s&   € Ý/áÓ˜eÒ#Ü˜$ÓÐä˜$ÓÐr   c                   ó,   — e Zd ZdZ	 	 	 	 dd„Zd„ Zd„ Zy)ÚImageFolderaJ  A generic data loader where the samples are arranged in this way:

    .. code-block:: text

        root/1.ext
        root/2.ext
        root/sub_dir/3.ext

    Args:
        root (str): Root directory path.
        loader (Callable, optional): A function to load a sample given its path. Default: None.
        extensions (list[str]|tuple[str], optional): A list of allowed extensions.
            Both :attr:`extensions` and :attr:`is_valid_file` should not be passed.
            If this value is not set, the default is to use ('.jpg', '.jpeg', '.png',
            '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'). Default: None.
        transform (Callable, optional): A function/transform that takes in
            a sample and returns a transformed version. Default: None.
        is_valid_file (Callable, optional): A function that takes path of a file
            and check if the file is a valid file. Both :attr:`extensions` and
            :attr:`is_valid_file` should not be passed. Default: None.

    Returns:
        :ref:`api_paddle_io_Dataset`. An instance of ImageFolder.

    Attributes:
        samples (list[str]): List of sample path.

    Example:

        .. code-block:: python

            >>> import shutil
            >>> import tempfile
            >>> import cv2
            >>> import numpy as np
            >>> import paddle.vision.transforms as T
            >>> from pathlib import Path
            >>> from paddle.vision.datasets import ImageFolder


            >>> def make_fake_file(img_path: str):
            ...     if img_path.endswith((".jpg", ".png", ".jpeg")):
            ...         fake_img = np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8)
            ...         cv2.imwrite(img_path, fake_img)
            ...     elif img_path.endswith(".txt"):
            ...         with open(img_path, "w") as f:
            ...             f.write("This is a fake file.")

            >>> def make_directory(root, directory_hierarchy, file_maker=make_fake_file):
            ...     root = Path(root)
            ...     root.mkdir(parents=True, exist_ok=True)
            ...     for subpath in directory_hierarchy:
            ...         if isinstance(subpath, str):
            ...             filepath = root / subpath
            ...             file_maker(str(filepath))
            ...         else:
            ...             dirname = list(subpath.keys())[0]
            ...             make_directory(root / dirname, subpath[dirname])

            >>> directory_hierarchy = [
            ...     "abc.jpg",
            ...     "def.png",
            ...     {"ghi": [
            ...         "jkl.jpeg",
            ...         {"mno": [
            ...             "pqr.jpg"]}]},
            ...     "this_will_be_ignored.txt",
            ... ]

            >>> # You can replace this with any directory to explore the structure
            >>> # of generated data. e.g. fake_data_dir = "./temp_dir"
            >>> fake_data_dir = tempfile.mkdtemp()
            >>> make_directory(fake_data_dir, directory_hierarchy)
            >>> image_folder_1 = ImageFolder(fake_data_dir)
            >>> print(image_folder_1.samples)
            >>> # doctest: +SKIP(it's different with windows)
            ['./temp_dir/abc.jpg', './temp_dir/def.png',
             './temp_dir/ghi/jkl.jpeg', './temp_dir/ghi/mno/pqr.jpg']
            >>> # doctest: -SKIP
            >>> print(len(image_folder_1))
            4

            >>> for i in range(len(image_folder_1)):
            ...     (img,) = image_folder_1[i]
            ...     # do something with img
            ...     print(type(img), img.size)
            ...     # <class 'PIL.Image.Image'> (32, 32)


            >>> transform = T.Compose(
            ...     [
            ...         T.Resize(64),
            ...         T.ToTensor(),
            ...         T.Normalize(
            ...             mean=[0.5, 0.5, 0.5],
            ...             std=[0.5, 0.5, 0.5],
            ...             to_rgb=True,
            ...         ),
            ...     ]
            ... )

            >>> image_folder_2 = ImageFolder(
            ...     fake_data_dir,
            ...     loader=lambda x: cv2.imread(x),  # load image with OpenCV
            ...     extensions=(".jpg",),  # only load *.jpg files
            ...     transform=transform,  # apply transform to every image
            ... )

            >>> print(image_folder_2.samples)
            >>> # doctest: +SKIP(it's different with windows)
            ['./temp_dir/abc.jpg', './temp_dir/ghi/mno/pqr.jpg']
            >>> # doctest: -SKIP
            >>> print(len(image_folder_2))
            2

            >>> for (img,) in iter(image_folder_2):
            ...     # do something with img
            ...     print(type(img), img.shape)
            ...     # <class 'paddle.Tensor'> [3, 64, 64]

            >>> shutil.rmtree(fake_data_dir)
    Nc                 ó  ‡— || _         ‰€t        Šg }t        j                  j	                  |«      }‰�ˆfd„}t        t        j                  |d¬«      «      D ]P  \  }}}	t        |	«      D ]<  }
t        j                  j                  ||
«      } ||«      sŒ,|j                  |«       Œ> ŒR t        |«      dk(  r-t        d| j                   z   dz   dj                  ‰«      z   «      ‚|€t        n|| _        ‰| _        || _        || _        y )Nc                 ó   •— t        | ‰«      S r   r   r   s    €r   r   z+ImageFolder.__init__.<locals>.is_valid_fileÃ  s   ø€ Ü*¨1¨jÓ9Ð9r   Tr   r   z Found 0 files in subfolders of: r1   r2   )r(   r5   r   r   r   r   r!   r   r"   r7   r8   r9   r:   r   r<   r4   )rA   r(   r:   r   r4   r   r<   r   r)   r*   r+   r`   s      `        r   rC   zImageFolder.__init__²  sü   ø€ ð ˆŒ	ØÐÜ'ˆJàˆÜ�w‰w×!Ñ! $Ó'ˆàÐ!ô:ô  &¤b§g¡g¨dÀÔ&EÖF‰OˆD�!�VÜ ž�Ü—G‘G—L‘L  uÓ-�Ù  Õ#Ø—N‘N 1Õ%ñ (ð  Gô ˆw‹<˜1ÒäØ6¸¿¹ÑBð F1ñ 1Ø36·8±8¸JÓ3GñHóðð )/¨•n¸FˆŒØ$ˆŒØˆŒØ"ˆ�r   c                 ó‚   — | j                   |   }| j                  |«      }| j                  �| j                  |«      }|gS )zn
        Args:
            index (int): Index

        Returns:
            sample of specific index.
        rL   )rA   rM   r   rN   s       r   rO   zImageFolder.__getitem__Ù  s?   € ð �|‰|˜EÑ"ˆØ—‘˜TÓ"ˆØ�>‰>Ð%Ø—^‘^ FÓ+ˆFØˆxˆr   c                 ó,   — t        | j                  «      S r   rQ   rR   s    r   rS   zImageFolder.__len__ç  rT   r   rU   )rV   rW   rX   rY   rC   rO   rS   rZ   r   r   rm   rm   6  s'   „ ñyð| ØØØó%#òNó!r   rm   r   )r   ÚPILr   r>   Ú	paddle.ior   Úpaddle.utilsr   Ú__all__r   r-   r/   r5   rb   rh   r9   rm   rZ   r   r   Ú<module>rv      sX   ðó 
å ã Ý Ý #à
€ò1ó"ô.P!�Gô P!ðf
€ò"ò=ò
 ôr!�'õ r!r   