




'''simple docstring'''
import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile
from typing import List

from datasets import config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadMode
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.info_utils import VerificationMode
def 				snake_case_  (   a__		:	int    ,**a__		:	Any			):



    """simple docstring"""




    return RunBeamCommand(
        args.dataset    ,args.name    ,args.cache_dir    ,args.beam_pipeline_options    ,args.data_dir    ,args.all_configs    ,args.save_info or args.save_infos    ,args.ignore_verifications    ,args.force_redownload    ,**a__    ,)






class        SCREAMING_SNAKE_CASE(				__A     ):

       @staticmethod
       def     snake_case__			(    lowerCamelCase__     )    ->					Tuple:

           """simple docstring"""



           __lowercase							=						parser.add_parser("""run_beam"""					,		help="""Run a Beam dataset processing pipeline"""     )
           run_beam_parser.add_argument("""dataset"""					,		type=lowerCamelCase__					,		help="""Name of the dataset to download"""     )
           run_beam_parser.add_argument("""--name"""					,		type=lowerCamelCase__					,		default=lowerCamelCase__					,		help="""Dataset config name"""     )
           run_beam_parser.add_argument(
               """--cache_dir"""					,		type=lowerCamelCase__					,		default=lowerCamelCase__					,		help="""Cache directory where the datasets are stored"""					,		)
           run_beam_parser.add_argument(
               """--beam_pipeline_options"""					,		type=lowerCamelCase__					,		default=""""""					,		help="""Beam pipeline options, separated by commas. Example:: `--beam_pipeline_options=job_name=my-job,project=my-project`"""					,		)
           run_beam_parser.add_argument(
               """--data_dir"""					,		type=lowerCamelCase__					,		default=lowerCamelCase__					,		help="""Can be used to specify a manual directory to get the files from"""					,		)
           run_beam_parser.add_argument("""--all_configs"""					,		action="""store_true"""					,		help="""Test all dataset configurations"""     )
           run_beam_parser.add_argument("""--save_info"""					,		action="""store_true"""					,		help="""Save the dataset infos file"""     )
           run_beam_parser.add_argument(
               """--ignore_verifications"""					,		action="""store_true"""					,		help="""Run the test without checksums and splits checks"""     )
           run_beam_parser.add_argument("""--force_redownload"""					,		action="""store_true"""					,		help="""Force dataset redownload"""     )
           # aliases
           run_beam_parser.add_argument("""--save_infos"""					,		action="""store_true"""					,		help="""alias for save_info"""     )
           run_beam_parser.set_defaults(func=lowerCamelCase__     )

       def __init__(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		**lowerCamelCase__					,		)    ->					Tuple:

           """simple docstring"""



           __lowercase							=						dataset
           __lowercase							=						name
           __lowercase							=						cache_dir
           __lowercase							=						beam_pipeline_options
           __lowercase							=						data_dir
           __lowercase							=						all_configs
           __lowercase							=						save_infos
           __lowercase							=						ignore_verifications
           __lowercase							=						force_redownload
           __lowercase							=						config_kwargs




       def     snake_case__			(    self     )    ->					Union[str, Any]:

           """simple docstring"""



           import apache_beam as beam

           if self._name is not None and self._all_configs:
               print("""Both parameters `name` and `all_configs` can't be used at once."""     )
               exit(1     )
           __lowercase				,__lowercase							=						self._dataset, self._name
           __lowercase							=						dataset_module_factory(lowerCamelCase__     )
           __lowercase							=						import_main_class(dataset_module.module_path     )
           __lowercase							=						[]
           if self._beam_pipeline_options:
               __lowercase							=						beam.options.pipeline_options.PipelineOptions(
                   flags=[F'--{opt.strip()}' for opt in self._beam_pipeline_options.split(""","""     ) if opt]     )
           else:
               __lowercase							=						None
           if self._all_configs and len(builder_cls.BUILDER_CONFIGS     ) > 0:
               for builder_config in builder_cls.BUILDER_CONFIGS:
                   builders.append(
                       builder_cls(
                           config_name=builder_config.name					,		data_dir=self._data_dir					,		hash=dataset_module.hash					,		beam_options=lowerCamelCase__					,		cache_dir=self._cache_dir					,		base_path=dataset_module.builder_kwargs.get("""base_path"""     )					,		)     )
           else:
               builders.append(
                   builder_cls(
                       config_name=lowerCamelCase__					,		data_dir=self._data_dir					,		beam_options=lowerCamelCase__					,		cache_dir=self._cache_dir					,		base_path=dataset_module.builder_kwargs.get("""base_path"""     )					,		**self._config_kwargs					,		)     )

           for builder in builders:
               builder.download_and_prepare(
                   download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
                   if not self._force_redownload
                   else DownloadMode.FORCE_REDOWNLOAD					,		download_config=DownloadConfig(cache_dir=config.DOWNLOADED_DATASETS_PATH     )					,		verification_mode=VerificationMode.NO_CHECKS
                   if self._ignore_verifications
                   else VerificationMode.ALL_CHECKS					,		try_from_hf_gcs=lowerCamelCase__					,		)
               if self._save_infos:
                   builder._save_infos()

           print("""Apache beam run successful."""     )

           # If save_infos=True, the dataset infos file is created next to the loaded module file.
           # 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:
               __lowercase							=						os.path.join(builder_cls.get_imported_module_dir()					,		config.DATASETDICT_INFOS_FILENAME     )

               __lowercase							=						Path(lowerCamelCase__     ).name + """.py"""

               __lowercase							=						os.path.join(lowerCamelCase__					,		lowerCamelCase__     )
               if os.path.isfile(lowerCamelCase__     ):
                   __lowercase							=						os.path.dirname(lowerCamelCase__     )
               elif os.path.isfile(lowerCamelCase__     ):
                   __lowercase							=						path
               else:  # in case of a remote dataset
                   print(F'Dataset Infos file saved at {dataset_infos_path}'     )
                   exit(1     )

               # Move datasetinfo back to the user
               __lowercase							=						os.path.join(lowerCamelCase__					,		config.DATASETDICT_INFOS_FILENAME     )
               copyfile(lowerCamelCase__					,		lowerCamelCase__     )
               print(F'Dataset Infos file saved at {user_dataset_infos_path}'     )










'''simple docstring'''
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        SCREAMING_SNAKE_CASE(				unittest.TestCase     ):

       def __init__(    self					,		lowerCamelCase__					,		lowerCamelCase__=7					,		lowerCamelCase__=3					,		lowerCamelCase__=18					,		lowerCamelCase__=30					,		lowerCamelCase__=400					,		lowerCamelCase__=True					,		lowerCamelCase__=None					,		lowerCamelCase__=True					,		lowerCamelCase__=False					,		lowerCamelCase__=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]					,		lowerCamelCase__=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]					,		lowerCamelCase__=True					,		)    ->					Union[str, Any]:

           """simple docstring"""



           __lowercase							=						size if size is not None else {"""height""": 20, """width""": 20}
           __lowercase							=						parent
           __lowercase							=						batch_size
           __lowercase							=						num_channels
           __lowercase							=						image_size
           __lowercase							=						min_resolution
           __lowercase							=						max_resolution
           __lowercase							=						do_resize
           __lowercase							=						size
           __lowercase							=						do_normalize
           __lowercase							=						image_mean
           __lowercase							=						image_std
           __lowercase							=						do_pad
           __lowercase							=						do_convert_rgb

       def     snake_case__			(    self     )    ->					Optional[int]:

           """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     snake_case__			(    self					,		lowerCamelCase__=False					,		lowerCamelCase__=False					,		lowerCamelCase__=False     )    ->					Tuple:

           """simple docstring"""



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

           if equal_resolution:
               __lowercase							=						[]
               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:
               __lowercase							=						[]
               for i in range(self.batch_size     ):
                   __lowercase				,__lowercase							=						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
               __lowercase							=						[Image.fromarray(np.moveaxis(lowerCamelCase__					,		0					,		-1     )     ) for x in image_inputs]

           if torchify:
               __lowercase							=						[torch.from_numpy(lowerCamelCase__     ) for x in image_inputs]

           return image_inputs






@require_torch
@require_vision
class        SCREAMING_SNAKE_CASE(				__A   ,      unittest.TestCase     ):
       snake_case_ :     Optional[int]    =					BlipImageProcessor if is_vision_available() else None

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

           """simple docstring"""



           __lowercase							=						BlipImageProcessingTester(self     )

       @property
       def     snake_case__			(    self     )    ->					Optional[int]:

           """simple docstring"""



           return self.image_processor_tester.prepare_image_processor_dict()

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

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_resize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""size"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_normalize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_mean"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_std"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_convert_rgb"""     )     )

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           pass

       def     snake_case__			(    self     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random PIL images
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		Image.Image     )

           # Test not batched input
           __lowercase							=						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
           __lowercase							=						image_processor(lowerCamelCase__					,		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     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random numpy tensors
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__					,		numpify=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		np.ndarray     )

           # Test not batched input
           __lowercase							=						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
           __lowercase							=						image_processor(lowerCamelCase__					,		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     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random PyTorch tensors
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__					,		torchify=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		torch.Tensor     )

           # Test not batched input
           __lowercase							=						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
           __lowercase							=						image_processor(lowerCamelCase__					,		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        SCREAMING_SNAKE_CASE(				__A   ,      unittest.TestCase     ):
       snake_case_ :     Union[str, Any]    =					BlipImageProcessor if is_vision_available() else None

       def     snake_case__			(    self     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						BlipImageProcessingTester(self					,		num_channels=4     )
           __lowercase							=						3

       @property
       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           return self.image_processor_tester.prepare_image_processor_dict()

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_resize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""size"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_normalize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_mean"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_std"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_convert_rgb"""     )     )

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           pass




       def     snake_case__			(    self     )    ->					Union[str, Any]:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random PIL images
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		Image.Image     )

           # Test not batched input
           __lowercase							=						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
           __lowercase							=						image_processor(lowerCamelCase__					,		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"""],
               )					,		)




