




'''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  lowerCamelCase(       SCREAMING_SNAKE_CASE_					,**SCREAMING_SNAKE_CASE_    )		->		int:
			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					,**SCREAMING_SNAKE_CASE_					,)






class      __UpperCAmelCase							(    lowerCAmelCase							):



					'''simple docstring'''





					@staticmethod
					def 						__snake_case	(  _lowercase    :	ArgumentParser)						->       int:
								A_       		=   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    :	List[Any]			,					_lowercase    :	str			,					_lowercase    :	str			,					_lowercase    :	str			,					_lowercase    :	str			,					_lowercase    :	str			,					_lowercase    :	bool			,					_lowercase    :	bool			,					_lowercase    :	bool			,					_lowercase    :	bool			,					**_lowercase    :	Any			,					)						->       List[Any]:
								A_       		=   dataset
								A_       		=   name
								A_       		=   cache_dir
								A_       		=   beam_pipeline_options
								A_       		=   data_dir
								A_       		=   all_configs
								A_       		=   save_infos
								A_       		=   ignore_verifications
								A_       		=   force_redownload
								A_       		=   config_kwargs



					def 						__snake_case	(  self    :	Any)						->       Dict:
								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_		,   A_       		=   self._dataset, self._name
								A_       		=   dataset_module_factory(_lowercase)
								A_       		=   import_main_class(dataset_module.module_path)
								A_       		=   []
								if self._beam_pipeline_options:
											A_       		=   beam.options.pipeline_options.PipelineOptions(
											    flags=[F'--{opt.strip()}' for opt in self._beam_pipeline_options.split(',') if opt])
								else:
											A_       		=   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_       		=   os.path.join(builder_cls.get_imported_module_dir()			,					config.DATASETDICT_INFOS_FILENAME)

											A_       		=   Path(_lowercase).name + '.py'

											A_       		=   os.path.join(_lowercase			,					_lowercase)
											if os.path.isfile(_lowercase):
														A_       		=   os.path.dirname(_lowercase)
											elif os.path.isfile(_lowercase):
														A_       		=   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_       		=   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      __UpperCAmelCase							(    unittest.TestCase							):



					'''simple docstring'''





					def __init__(  self    :	Dict			,					_lowercase    :	List[Any]			,					_lowercase    :	List[Any]=7			,					_lowercase    :	Dict=3			,					_lowercase    :	List[Any]=18			,					_lowercase    :	List[str]=30			,					_lowercase    :	List[str]=400			,					_lowercase    :	Any=True			,					_lowercase    :	Any=None			,					_lowercase    :	Any=True			,					_lowercase    :	Dict=None			,					_lowercase    :	Optional[int]=True			,					_lowercase    :	int=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]			,					_lowercase    :	Any=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]			,					_lowercase    :	Optional[Any]=True			,					)						->       List[str]:
								A_       		=   size if size is not None else {'shortest_edge': 20}
								A_       		=   crop_size if crop_size is not None else {'height': 18, 'width': 18}
								A_       		=   parent
								A_       		=   batch_size
								A_       		=   num_channels
								A_       		=   image_size
								A_       		=   min_resolution
								A_       		=   max_resolution
								A_       		=   do_resize
								A_       		=   size
								A_       		=   do_center_crop
								A_       		=   crop_size
								A_       		=   do_normalize
								A_       		=   image_mean
								A_       		=   image_std
								A_       		=   do_convert_rgb



					def 						__snake_case	(  self    :	Optional[Any])						->       List[Any]:
								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 						__snake_case	(  self    :	Dict			,					_lowercase    :	Tuple=False			,					_lowercase    :	Tuple=False			,					_lowercase    :	Union[str, Any]=False)						->       List[Any]:
								assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

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

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

								return image_inputs





@require_torch
@require_vision
class      __UpperCAmelCase							(    lowerCAmelCase ,unittest.TestCase							):



					'''simple docstring'''





					_UpperCamelCase  	=		CLIPImageProcessor if is_vision_available() else None



					def 						__snake_case	(  self    :	Optional[Any])						->       List[str]:
								A_       		=   CLIPImageProcessingTester(self)



					@property
					def 						__snake_case	(  self    :	Dict)						->       Optional[Any]:
								return self.image_processor_tester.prepare_image_processor_dict()



					def 						__snake_case	(  self    :	Optional[Any])						->       str:
								A_       		=   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 						__snake_case	(  self    :	Union[str, Any])						->       Optional[int]:
								A_       		=   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_       		=   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 						__snake_case	(  self    :	str)						->       List[str]:
								pass



					def 						__snake_case	(  self    :	List[str])						->       Dict:
								# Initialize image_processing
								A_       		=   self.image_processing_class(**self.image_processor_dict)
								# create random PIL images
								A_       		=   self.image_processor_tester.prepare_inputs(equal_resolution=_lowercase)
								for image in image_inputs:
											self.assertIsInstance(_lowercase			,					Image.Image)

								# Test not batched input
								A_       		=   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_       		=   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 						__snake_case	(  self    :	Union[str, Any])						->       Dict:
								# Initialize image_processing
								A_       		=   self.image_processing_class(**self.image_processor_dict)
								# create random numpy tensors
								A_       		=   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_       		=   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_       		=   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 						__snake_case	(  self    :	Optional[Any])						->       Tuple:
								# Initialize image_processing
								A_       		=   self.image_processing_class(**self.image_processor_dict)
								# create random PyTorch tensors
								A_       		=   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_       		=   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_       		=   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      __UpperCAmelCase							(    lowerCAmelCase ,unittest.TestCase							):



					'''simple docstring'''





					_UpperCamelCase  	=		CLIPImageProcessor if is_vision_available() else None



					def 						__snake_case	(  self    :	int)						->       List[Any]:
								A_       		=   CLIPImageProcessingTester(self			,					num_channels=4)
								A_       		=   3



					@property
					def 						__snake_case	(  self    :	str)						->       Tuple:
								return self.image_processor_tester.prepare_image_processor_dict()



					def 						__snake_case	(  self    :	Any)						->       Dict:
								A_       		=   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 						__snake_case	(  self    :	Any)						->       Optional[int]:
								pass



					def 						__snake_case	(  self    :	str)						->       List[Any]:
								# Initialize image_processing
								A_       		=   self.image_processing_class(**self.image_processor_dict)
								# create random PIL images
								A_       		=   self.image_processor_tester.prepare_inputs(equal_resolution=_lowercase)
								for image in image_inputs:
											self.assertIsInstance(_lowercase			,					Image.Image)

								# Test not batched input
								A_       		=   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_       		=   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'],
								    )			,					)




