

import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile, rmtree
from typing import Generator

import datasets.config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.download.download_manager import DownloadMode
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.filelock import logger as fl_logger
from datasets.utils.info_utils import VerificationMode
from datasets.utils.logging import ERROR, get_logger


_UpperCamelCase			      =		get_logger(__name__)







def 		_lowercase			(					lowercase__						):
      return TestCommand(
          args.dataset       ,     args.name       ,     args.cache_dir       ,     args.data_dir       ,     args.all_configs       ,     args.save_info or args.save_infos       ,     args.ignore_verifications       ,     args.force_redownload       ,     args.clear_cache       ,     )







class   __lowercase				(_UpperCAmelCase			):
 _UpperCamelCase        =  False  # to tell pytest it's not a test class
 @staticmethod
 def      UpperCamelCase__  (							A_ ) ->str:



       '''simple docstring'''





       __lowerCAmelCase :						int = parser.add_parser('''test'''				,							help='''Test dataset implementation.''' )
       test_parser.add_argument('''--name'''				,							type=A_				,							default=A_				,							help='''Dataset processing name''' )
       test_parser.add_argument(
           '''--cache_dir'''				,							type=A_				,							default=A_				,							help='''Cache directory where the datasets are stored.'''				,							)
       test_parser.add_argument(
           '''--data_dir'''				,							type=A_				,							default=A_				,							help='''Can be used to specify a manual directory to get the files from.'''				,							)
       test_parser.add_argument('''--all_configs'''				,							action='''store_true'''				,							help='''Test all dataset configurations''' )
       test_parser.add_argument(
           '''--save_info'''				,							action='''store_true'''				,							help='''Save the dataset infos in the dataset card (README.md)''' )
       test_parser.add_argument(
           '''--ignore_verifications'''				,							action='''store_true'''				,							help='''Run the test without checksums and splits checks.'''				,							)
       test_parser.add_argument('''--force_redownload'''				,							action='''store_true'''				,							help='''Force dataset redownload''' )
       test_parser.add_argument(
           '''--clear_cache'''				,							action='''store_true'''				,							help='''Remove downloaded files and cached datasets after each config test'''				,							)
       # aliases
       test_parser.add_argument('''--save_infos'''				,							action='''store_true'''				,							help='''alias to save_info''' )
       test_parser.add_argument('''dataset'''				,							type=A_				,							help='''Name of the dataset to download''' )
       test_parser.set_defaults(func=_test_command_factory )
 def __init__(							self				,							A_				,							A_				,							A_				,							A_				,							A_				,							A_				,							A_				,							A_				,							A_				,							) ->List[str]:



       '''simple docstring'''





       __lowerCAmelCase :						Dict = dataset
       __lowerCAmelCase :						Dict = name
       __lowerCAmelCase :						str = cache_dir
       __lowerCAmelCase :						Optional[Any] = data_dir
       __lowerCAmelCase :						int = all_configs
       __lowerCAmelCase :						Optional[int] = save_infos
       __lowerCAmelCase :						Optional[Any] = ignore_verifications
       __lowerCAmelCase :						Optional[Any] = force_redownload
       __lowerCAmelCase :						Optional[int] = clear_cache
       if clear_cache and not cache_dir:
             print(
                 '''When --clear_cache is used, specifying a cache directory is mandatory.\n'''
                 '''The \'download\' folder of the cache directory and the dataset builder cache will be deleted after each configuration test.\n'''
                 '''Please provide a --cache_dir that will be used to test the dataset script.''' )
             exit(1 )
       if save_infos:
             __lowerCAmelCase :						Tuple = True





 def      UpperCamelCase__  (							self ) ->str:



       '''simple docstring'''





       fl_logger().setLevel(A_ )
       if self._name is not None and self._all_configs:
             print('''Both parameters `config` and `all_configs` can\'t be used at once.''' )
             exit(1 )
       __lowerCAmelCase :						Optional[int] = self._dataset, self._name
       __lowerCAmelCase :						Tuple = dataset_module_factory(A_ )
       __lowerCAmelCase :						Dict = import_main_class(module.module_path )
       __lowerCAmelCase :						Dict = len(builder_cls.BUILDER_CONFIGS ) if self._all_configs and builder_cls.BUILDER_CONFIGS else 1

       def get_builders() -> Generator[DatasetBuilder, None, None]:
             if self._all_configs and builder_cls.BUILDER_CONFIGS:
                   for i, config in enumerate(builder_cls.BUILDER_CONFIGS ):
                         if "config_name" in module.builder_kwargs:
                               yield builder_cls(
                                   cache_dir=self._cache_dir				,							data_dir=self._data_dir				,							**module.builder_kwargs				,							)
                         else:
                               yield builder_cls(
                                   config_name=config.name				,							cache_dir=self._cache_dir				,							data_dir=self._data_dir				,							**module.builder_kwargs				,							)
             else:
                   if "config_name" in module.builder_kwargs:
                         yield builder_cls(cache_dir=self._cache_dir				,							data_dir=self._data_dir				,							**module.builder_kwargs )
                   else:
                         yield builder_cls(
                             config_name=A_				,							cache_dir=self._cache_dir				,							data_dir=self._data_dir				,							**module.builder_kwargs				,							)

       for j, builder in enumerate(get_builders() ):
             print(f"""Testing builder '{builder.config.name}' ({j + 1}/{n_builders})""" )
             __lowerCAmelCase :						int = os.path.exists(
                 os.path.join(builder.get_imported_module_dir()				,							datasets.config.DATASETDICT_INFOS_FILENAME ) )  # record checksums only if we need to update a (deprecated) dataset_infos.json
             builder.download_and_prepare(
                 download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
                 if not self._force_redownload
                 else DownloadMode.FORCE_REDOWNLOAD				,							verification_mode=VerificationMode.NO_CHECKS
                 if self._ignore_verifications
                 else VerificationMode.ALL_CHECKS				,							try_from_hf_gcs=A_				,							)
             builder.as_dataset()
             if self._save_infos:
                   builder._save_infos()

             # If save_infos=True, the dataset card (README.md) is created next to the loaded module file.
             # The dataset_infos are saved in the YAML part of the README.md

             # Let's move it to the original directory of the dataset script, to allow the user to
             # upload them on S3 at the same time afterwards.
             if self._save_infos:
                   __lowerCAmelCase :						str = os.path.join(builder_cls.get_imported_module_dir()				,							'''README.md''' )
                   __lowerCAmelCase :						Dict = Path(A_ ).name + '''.py'''
                   __lowerCAmelCase :						Optional[int] = os.path.join(A_				,							A_ )
                   if os.path.isfile(A_ ):
                         __lowerCAmelCase :						Union[str, Any] = os.path.dirname(A_ )
                   elif os.path.isfile(A_ ):
                         __lowerCAmelCase :						int = path
                   elif os.path.isdir(A_ ):  # for local directories containing only data files
                         __lowerCAmelCase :						List[Any] = path
                   else:  # in case of a remote dataset
                         __lowerCAmelCase :						List[str] = None
                         print(f"""Dataset card saved at {dataset_readme_path}""" )

                   # Move dataset_info back to the user
                   if dataset_dir is not None:
                         __lowerCAmelCase :						Optional[int] = os.path.join(A_				,							'''README.md''' )
                         copyfile(A_				,							A_ )
                         print(f"""Dataset card saved at {user_dataset_readme_path}""" )

            # If clear_cache=True, the download folder and the dataset builder cache directory are deleted
             if self._clear_cache:
                   if os.path.isdir(builder._cache_dir ):
                         logger.warning(f"""Clearing cache at {builder._cache_dir}""" )
                         rmtree(builder._cache_dir )
                   __lowerCAmelCase :						int = os.path.join(self._cache_dir				,							datasets.config.DOWNLOADED_DATASETS_DIR )
                   if os.path.isdir(A_ ):
                         logger.warning(f"""Clearing cache at {download_dir}""" )
                         rmtree(A_ )

       print('''Test successful.''' )





import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import BlipImageProcessor







class   __lowercase				(unittest.TestCase			):
 def __init__(							self				,							A_				,							A_=7				,							A_=3				,							A_=18				,							A_=30				,							A_=400				,							A_=True				,							A_=None				,							A_=True				,							A_=False				,							A_=[0.48_145_466, 0.4_578_275, 0.40_821_073]				,							A_=[0.26_862_954, 0.26_130_258, 0.27_577_711]				,							A_=True				,							) ->Dict:



       '''simple docstring'''





       __lowerCAmelCase :						Union[str, Any] = size if size is not None else {'''height''': 20, '''width''': 20}
       __lowerCAmelCase :						List[str] = parent
       __lowerCAmelCase :						List[str] = batch_size
       __lowerCAmelCase :						Optional[Any] = num_channels
       __lowerCAmelCase :						List[Any] = image_size
       __lowerCAmelCase :						Optional[int] = min_resolution
       __lowerCAmelCase :						Optional[int] = max_resolution
       __lowerCAmelCase :						List[Any] = do_resize
       __lowerCAmelCase :						Dict = size
       __lowerCAmelCase :						Dict = do_normalize
       __lowerCAmelCase :						Any = image_mean
       __lowerCAmelCase :						Optional[int] = image_std
       __lowerCAmelCase :						Any = do_pad
       __lowerCAmelCase :						Any = do_convert_rgb
 def      UpperCamelCase__  (							self ) ->List[str]:



       '''simple docstring'''





       return {
           "do_resize": self.do_resize,
           "size": self.size,
           "do_normalize": self.do_normalize,
           "image_mean": self.image_mean,
           "image_std": self.image_std,
           "do_convert_rgb": self.do_convert_rgb,
           "do_pad": self.do_pad,
       }





 def      UpperCamelCase__  (							self				,							A_=False				,							A_=False				,							A_=False ) ->Dict:



       '''simple docstring'''





       assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

       if equal_resolution:
             __lowerCAmelCase :						int = []
             for i in range(self.batch_size ):
                   image_inputs.append(
                       np.random.randint(
                           255				,							size=(self.num_channels, self.max_resolution, self.max_resolution)				,							dtype=np.uinta ) )
       else:
             __lowerCAmelCase :						List[Any] = []
             for i in range(self.batch_size ):
                   __lowerCAmelCase,							__lowerCAmelCase :						Any = np.random.choice(np.arange(self.min_resolution				,							self.max_resolution )				,							2 )
                   image_inputs.append(np.random.randint(255				,							size=(self.num_channels, width, height)				,							dtype=np.uinta ) )

       if not numpify and not torchify:
             # PIL expects the channel dimension as last dimension
             __lowerCAmelCase :						List[str] = [Image.fromarray(np.moveaxis(A_				,							0				,							-1 ) ) for x in image_inputs]

       if torchify:
             __lowerCAmelCase :						int = [torch.from_numpy(A_ ) for x in image_inputs]

       return image_inputs







@require_torch
@require_vision
class   __lowercase				(_UpperCAmelCase		,       unittest.TestCase			):
 _UpperCamelCase        =  BlipImageProcessor if is_vision_available() else None
 def      UpperCamelCase__  (							self ) ->Tuple:



       '''simple docstring'''





       __lowerCAmelCase :						Union[str, Any] = BlipImageProcessingTester(self )
 @property
 def      UpperCamelCase__  (							self ) ->int:



       '''simple docstring'''





       return self.image_processor_tester.prepare_image_processor_dict()
 def      UpperCamelCase__  (							self ) ->int:



       '''simple docstring'''





       __lowerCAmelCase :						str = self.image_processing_class(**self.image_processor_dict )
       self.assertTrue(hasattr(A_				,							'''do_resize''' ) )
       self.assertTrue(hasattr(A_				,							'''size''' ) )
       self.assertTrue(hasattr(A_				,							'''do_normalize''' ) )
       self.assertTrue(hasattr(A_				,							'''image_mean''' ) )
       self.assertTrue(hasattr(A_				,							'''image_std''' ) )
       self.assertTrue(hasattr(A_				,							'''do_convert_rgb''' ) )
 def      UpperCamelCase__  (							self ) ->str:



       '''simple docstring'''





       pass
 def      UpperCamelCase__  (							self ) ->List[Any]:



       '''simple docstring'''





       __lowerCAmelCase :						Dict = self.image_processing_class(**self.image_processor_dict )
       # create random PIL images
       __lowerCAmelCase :						List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=A_ )
       for image in image_inputs:
             self.assertIsInstance(A_				,							Image.Image )

       # Test not batched input
       __lowerCAmelCase :						Optional[Any] = image_processor(image_inputs[0]				,							return_tensors='''pt''' ).pixel_values
       self.assertEqual(
           encoded_images.shape				,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           )				,							)

       # Test batched
       __lowerCAmelCase :						str = image_processor(A_				,							return_tensors='''pt''' ).pixel_values
       self.assertEqual(
           encoded_images.shape				,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           )				,							)
 def      UpperCamelCase__  (							self ) ->Union[str, Any]:



       '''simple docstring'''





       __lowerCAmelCase :						Optional[Any] = self.image_processing_class(**self.image_processor_dict )
       # create random numpy tensors
       __lowerCAmelCase :						Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=A_				,							numpify=A_ )
       for image in image_inputs:
             self.assertIsInstance(A_				,							np.ndarray )

       # Test not batched input
       __lowerCAmelCase :						Dict = image_processor(image_inputs[0]				,							return_tensors='''pt''' ).pixel_values
       self.assertEqual(
           encoded_images.shape				,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           )				,							)

       # Test batched
       __lowerCAmelCase :						List[Any] = image_processor(A_				,							return_tensors='''pt''' ).pixel_values
       self.assertEqual(
           encoded_images.shape				,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           )				,							)





 def      UpperCamelCase__  (							self ) ->List[Any]:



       '''simple docstring'''





       __lowerCAmelCase :						List[Any] = self.image_processing_class(**self.image_processor_dict )
       # create random PyTorch tensors
       __lowerCAmelCase :						str = self.image_processor_tester.prepare_inputs(equal_resolution=A_				,							torchify=A_ )
       for image in image_inputs:
             self.assertIsInstance(A_				,							torch.Tensor )

       # Test not batched input
       __lowerCAmelCase :						List[Any] = image_processor(image_inputs[0]				,							return_tensors='''pt''' ).pixel_values
       self.assertEqual(
           encoded_images.shape				,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           )				,							)

       # Test batched
       __lowerCAmelCase :						Tuple = image_processor(A_				,							return_tensors='''pt''' ).pixel_values
       self.assertEqual(
           encoded_images.shape				,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           )				,							)







@require_torch
@require_vision
class   __lowercase				(_UpperCAmelCase		,       unittest.TestCase			):
 _UpperCamelCase        =  BlipImageProcessor if is_vision_available() else None
 def      UpperCamelCase__  (							self ) ->Optional[Any]:



       '''simple docstring'''





       __lowerCAmelCase :						Any = BlipImageProcessingTester(self				,							num_channels=4 )
       __lowerCAmelCase :						str = 3
 @property
 def      UpperCamelCase__  (							self ) ->List[str]:



       '''simple docstring'''





       return self.image_processor_tester.prepare_image_processor_dict()
 def      UpperCamelCase__  (							self ) ->Tuple:



       '''simple docstring'''





       __lowerCAmelCase :						int = self.image_processing_class(**self.image_processor_dict )
       self.assertTrue(hasattr(A_				,							'''do_resize''' ) )
       self.assertTrue(hasattr(A_				,							'''size''' ) )
       self.assertTrue(hasattr(A_				,							'''do_normalize''' ) )
       self.assertTrue(hasattr(A_				,							'''image_mean''' ) )
       self.assertTrue(hasattr(A_				,							'''image_std''' ) )
       self.assertTrue(hasattr(A_				,							'''do_convert_rgb''' ) )
 def      UpperCamelCase__  (							self ) ->Union[str, Any]:



       '''simple docstring'''





       pass





 def      UpperCamelCase__  (							self ) ->Any:



       '''simple docstring'''





       __lowerCAmelCase :						Tuple = self.image_processing_class(**self.image_processor_dict )
       # create random PIL images
       __lowerCAmelCase :						Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=A_ )
       for image in image_inputs:
             self.assertIsInstance(A_				,							Image.Image )

       # Test not batched input
       __lowerCAmelCase :						Tuple = image_processor(image_inputs[0]				,							return_tensors='''pt''' ).pixel_values
       self.assertEqual(
           encoded_images.shape				,							(
               1,
               self.expected_encoded_image_num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           )				,							)

       # Test batched
       __lowerCAmelCase :						List[str] = image_processor(A_				,							return_tensors='''pt''' ).pixel_values
       self.assertEqual(
           encoded_images.shape				,							(
               self.image_processor_tester.batch_size,
               self.expected_encoded_image_num_channels,
               self.image_processor_tester.size['''height'''],
               self.image_processor_tester.size['''width'''],
           )				,							)


