




'''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    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				Dict   ,						**UpperCamelCase__						:				Union[str, 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   ,						**lowerCAmelCase__   ,						)







class     SCREAMING_SNAKE_CASE						(	snake_case__							):






      @staticmethod
      def        lowercase_	(   lowercase__      :     ArgumentParser					):


           '''simple docstring'''

           a_    :       Tuple    	=     parser.add_parser("""run_beam"""	,	help="""Run a Beam dataset processing pipeline"""					)
           run_beam_parser.add_argument("""dataset"""	,	type=lowercase__	,	help="""Name of the dataset to download"""					)
           run_beam_parser.add_argument("""--name"""	,	type=lowercase__	,	default=lowercase__	,	help="""Dataset config name"""					)
           run_beam_parser.add_argument(
               """--cache_dir"""	,	type=lowercase__	,	default=lowercase__	,	help="""Cache directory where the datasets are stored"""	,	)
           run_beam_parser.add_argument(
               """--beam_pipeline_options"""	,	type=lowercase__	,	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=lowercase__	,	default=lowercase__	,	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=lowercase__					)






      def __init__(   self      :     Optional[Any]	,	lowercase__      :     str	,	lowercase__      :     str	,	lowercase__      :     str	,	lowercase__      :     str	,	lowercase__      :     str	,	lowercase__      :     bool	,	lowercase__      :     bool	,	lowercase__      :     bool	,	lowercase__      :     bool	,	**lowercase__      :     Any	,	):


           '''simple docstring'''

           a_    :       int    	=     dataset
           a_    :       List[Any]    	=     name
           a_    :       List[Any]    	=     cache_dir
           a_    :       str    	=     beam_pipeline_options
           a_    :       Any    	=     data_dir
           a_    :       int    	=     all_configs
           a_    :       int    	=     save_infos
           a_    :       Optional[int]    	=     ignore_verifications
           a_    :       List[Any]    	=     force_redownload
           a_    :       Optional[Any]    	=     config_kwargs






      def        lowercase_	(   self      :     Optional[int]					):


           '''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					)
           a_    :       List[Any]    	=     self._dataset, self._name
           a_    :       List[Any]    	=     dataset_module_factory(lowercase__					)
           a_    :       Optional[int]    	=     import_main_class(dataset_module.module_path					)
           a_    :       List[DatasetBuilder]    	=     []
           if self._beam_pipeline_options:
                a_    :       str    	=     beam.options.pipeline_options.PipelineOptions(
                    flags=[F"--{opt.strip()}" for opt in self._beam_pipeline_options.split(""","""					) if opt]					)
           else:
                a_    :       Tuple    	=     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=lowercase__	,	cache_dir=self._cache_dir	,	base_path=dataset_module.builder_kwargs.get("""base_path"""					)	,	)					)
           else:
                builders.append(
                    builder_cls(
                        config_name=lowercase__	,	data_dir=self._data_dir	,	beam_options=lowercase__	,	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=lowercase__	,	)
                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:
                a_    :       Tuple    	=     os.path.join(builder_cls.get_imported_module_dir()	,	config.DATASETDICT_INFOS_FILENAME					)

                a_    :       str    	=     Path(lowercase__					).name + '.py'

                a_    :       List[str]    	=     os.path.join(lowercase__	,	lowercase__					)
                if os.path.isfile(lowercase__					):
                     a_    :       List[str]    	=     os.path.dirname(lowercase__					)
                elif os.path.isfile(lowercase__					):
                     a_    :       Tuple    	=     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
                a_    :       Tuple    	=     os.path.join(lowercase__	,	config.DATASETDICT_INFOS_FILENAME					)
                copyfile(lowercase__	,	lowercase__					)
                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 CLIPImageProcessor







class     SCREAMING_SNAKE_CASE						(	unittest.TestCase							):






      def __init__(   self      :     Tuple	,	lowercase__      :     Union[str, Any]	,	lowercase__      :     Optional[Any]=7	,	lowercase__      :     str=3	,	lowercase__      :     Tuple=18	,	lowercase__      :     Dict=30	,	lowercase__      :     List[Any]=400	,	lowercase__      :     Optional[Any]=True	,	lowercase__      :     Union[str, Any]=None	,	lowercase__      :     Union[str, Any]=True	,	lowercase__      :     Tuple=None	,	lowercase__      :     str=True	,	lowercase__      :     List[Any]=[0.48145466, 0.4578275, 0.40821073]	,	lowercase__      :     Optional[Any]=[0.26862954, 0.26130258, 0.27577711]	,	lowercase__      :     str=True	,	):


           '''simple docstring'''

           a_    :       Dict    	=     size if size is not None else {"""shortest_edge""": 20}
           a_    :       Any    	=     crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
           a_    :       List[str]    	=     parent
           a_    :       Dict    	=     batch_size
           a_    :       Any    	=     num_channels
           a_    :       Optional[int]    	=     image_size
           a_    :       Union[str, Any]    	=     min_resolution
           a_    :       Tuple    	=     max_resolution
           a_    :       int    	=     do_resize
           a_    :       List[str]    	=     size
           a_    :       Optional[int]    	=     do_center_crop
           a_    :       str    	=     crop_size
           a_    :       str    	=     do_normalize
           a_    :       Any    	=     image_mean
           a_    :       List[str]    	=     image_std
           a_    :       Any    	=     do_convert_rgb






      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

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






      def        lowercase_	(   self      :     str	,	lowercase__      :     Union[str, Any]=False	,	lowercase__      :     Union[str, Any]=False	,	lowercase__      :     Union[str, Any]=False					):


           '''simple docstring'''

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

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

           if torchify:
                a_    :       List[Any]    	=     [torch.from_numpy(lowercase__					) for x in image_inputs]

           return image_inputs







@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE						(	snake_case_       ,			unittest.TestCase							):
      __magic_name__     :					int             =				CLIPImageProcessor if is_vision_available() else None






      def        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           a_    :       Dict    	=     CLIPImageProcessingTester(self					)






      @property
      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()






      def        lowercase_	(   self      :     Optional[Any]					):


           '''simple docstring'''

           a_    :       List[Any]    	=     self.image_processing_class(**self.image_processor_dict					)
           self.assertTrue(hasattr(lowercase__	,	"""do_resize"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""size"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_center_crop"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""center_crop"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_normalize"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_mean"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_std"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_convert_rgb"""					)					)






      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           a_    :       Optional[Any]    	=     self.image_processing_class.from_dict(self.image_processor_dict					)
           self.assertEqual(image_processor.size	,	{"""shortest_edge""": 20}					)
           self.assertEqual(image_processor.crop_size	,	{"""height""": 18, """width""": 18}					)

           a_    :       Optional[int]    	=     self.image_processing_class.from_dict(self.image_processor_dict	,	size=42	,	crop_size=84					)
           self.assertEqual(image_processor.size	,	{"""shortest_edge""": 42}					)
           self.assertEqual(image_processor.crop_size	,	{"""height""": 84, """width""": 84}					)






      def        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

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

           # Test not batched input
           a_    :       Optional[Any]    	=     image_processing(image_inputs[0]	,	return_tensors="""pt"""					).pixel_values
           self.assertEqual(
               encoded_images.shape	,	(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)

           # Test batched
           a_    :       str    	=     image_processing(lowercase__	,	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.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

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

           # Test not batched input
           a_    :       Tuple    	=     image_processing(image_inputs[0]	,	return_tensors="""pt"""					).pixel_values
           self.assertEqual(
               encoded_images.shape	,	(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)

           # Test batched
           a_    :       str    	=     image_processing(lowercase__	,	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.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)






      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           a_    :       Dict    	=     self.image_processing_class(**self.image_processor_dict					)
           # create random PyTorch tensors
           a_    :       Optional[int]    	=     self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__	,	torchify=lowercase__					)
           for image in image_inputs:
                self.assertIsInstance(lowercase__	,	torch.Tensor					)

           # Test not batched input
           a_    :       Optional[int]    	=     image_processing(image_inputs[0]	,	return_tensors="""pt"""					).pixel_values
           self.assertEqual(
               encoded_images.shape	,	(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)

           # Test batched
           a_    :       int    	=     image_processing(lowercase__	,	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.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)







@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE						(	snake_case_       ,			unittest.TestCase							):
      __magic_name__     :					List[str]             =				CLIPImageProcessor if is_vision_available() else None






      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           a_    :       str    	=     CLIPImageProcessingTester(self	,	num_channels=4					)
           a_    :       Dict    	=     3






      @property
      def        lowercase_	(   self      :     Any					):


           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           a_    :       int    	=     self.image_processing_class(**self.image_processor_dict					)
           self.assertTrue(hasattr(lowercase__	,	"""do_resize"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""size"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_center_crop"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""center_crop"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_normalize"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_mean"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_std"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_convert_rgb"""					)					)






      def        lowercase_	(   self      :     int					):


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

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

           # Test not batched input
           a_    :       Optional[Any]    	=     image_processing(image_inputs[0]	,	return_tensors="""pt"""					).pixel_values
           self.assertEqual(
               encoded_images.shape	,	(
                   1,
                   self.expected_encoded_image_num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)

           # Test batched
           a_    :       List[str]    	=     image_processing(lowercase__	,	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.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)
