


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 			a_   (					SCREAMING_SNAKE_CASE__      :   Dict	,    **SCREAMING_SNAKE_CASE__      :   Optional[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	,    **SCREAMING_SNAKE_CASE__	,    )


class A						(     UpperCamelCase_  ):






      @staticmethod
      def  lowerCamelCase (      lowercase_		:  ArgumentParser				)      ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase :	str						=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[str]    ,     lowercase_		:  str    ,     lowercase_		:  str    ,     lowercase_		:  str    ,     lowercase_		:  str    ,     lowercase_		:  str    ,     lowercase_		:  bool    ,     lowercase_		:  bool    ,     lowercase_		:  bool    ,     lowercase_		:  bool    ,     **lowercase_		:  List[Any]    ,     )      ->		str:
             """simple docstring"""




             _lowerCamelCase :	Union[str, Any]						=dataset
             _lowerCamelCase :	int						=name
             _lowerCamelCase :	Optional[int]						=cache_dir
             _lowerCamelCase :	Optional[int]						=beam_pipeline_options
             _lowerCamelCase :	int						=data_dir
             _lowerCamelCase :	int						=all_configs
             _lowerCamelCase :	List[str]						=save_infos
             _lowerCamelCase :	Optional[Any]						=ignore_verifications
             _lowerCamelCase :	int						=force_redownload
             _lowerCamelCase :	Tuple						=config_kwargs






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

                    _lowerCamelCase :	Optional[int]						=Path(lowercase_				).name + '.py'

                    _lowerCamelCase :	Any						=os.path.join(lowercase_    ,     lowercase_				)
                    if os.path.isfile(lowercase_				):
                           _lowerCamelCase :	Optional[int]						=os.path.dirname(lowercase_				)
                    elif os.path.isfile(lowercase_				):
                           _lowerCamelCase :	List[str]						=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
                    _lowerCamelCase :	Dict						=os.path.join(lowercase_    ,     config.DATASETDICT_INFOS_FILENAME				)
                    copyfile(lowercase_    ,     lowercase_				)
                    print(F'''Dataset Infos file saved at {user_dataset_infos_path}'''				)






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, prepare_image_inputs


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import ConvNextImageProcessor




class A						(     unittest.TestCase  ):






      def __init__(      self		:  Optional[Any]    ,     lowercase_		:  str    ,     lowercase_		:  Tuple=7    ,     lowercase_		:  int=3    ,     lowercase_		:  Union[str, Any]=18    ,     lowercase_		:  Optional[int]=30    ,     lowercase_		:  Tuple=400    ,     lowercase_		:  str=True    ,     lowercase_		:  Dict=None    ,     lowercase_		:  Tuple=0.875    ,     lowercase_		:  List[Any]=True    ,     lowercase_		:  Union[str, Any]=[0.5, 0.5, 0.5]    ,     lowercase_		:  List[str]=[0.5, 0.5, 0.5]    ,     )      ->		Any:
             """simple docstring"""




             _lowerCamelCase :	Optional[Any]						=size if size is not None else {'shortest_edge': 20}
             _lowerCamelCase :	Optional[Any]						=parent
             _lowerCamelCase :	Union[str, Any]						=batch_size
             _lowerCamelCase :	Dict						=num_channels
             _lowerCamelCase :	Union[str, Any]						=image_size
             _lowerCamelCase :	Optional[int]						=min_resolution
             _lowerCamelCase :	Tuple						=max_resolution
             _lowerCamelCase :	Any						=do_resize
             _lowerCamelCase :	Dict						=size
             _lowerCamelCase :	int						=crop_pct
             _lowerCamelCase :	Dict						=do_normalize
             _lowerCamelCase :	int						=image_mean
             _lowerCamelCase :	Union[str, Any]						=image_std






      def  lowerCamelCase (      self		:  List[str]				)      ->		int:
             """simple docstring"""




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




@require_torch
@require_vision
class A						(     UpperCamelCase_					,							unittest.TestCase  ):
      UpperCamelCase__							:						List[Any]   =ConvNextImageProcessor if is_vision_available() else None






      def  lowerCamelCase (      self		:  List[str]				)      ->		Tuple:
             """simple docstring"""




             _lowerCamelCase :	Optional[Any]						=ConvNextImageProcessingTester(self				)






      @property
      def  lowerCamelCase (      self		:  List[str]				)      ->		int:
             """simple docstring"""




             return self.image_processor_tester.prepare_image_processor_dict()






      def  lowerCamelCase (      self		:  Optional[int]				)      ->		str:
             """simple docstring"""




             _lowerCamelCase :	Dict						=self.image_processing_class(**self.image_processor_dict				)
             self.assertTrue(hasattr(lowercase_    ,     'do_resize'				)				)
             self.assertTrue(hasattr(lowercase_    ,     'size'				)				)
             self.assertTrue(hasattr(lowercase_    ,     'crop_pct'				)				)
             self.assertTrue(hasattr(lowercase_    ,     'do_normalize'				)				)
             self.assertTrue(hasattr(lowercase_    ,     'image_mean'				)				)
             self.assertTrue(hasattr(lowercase_    ,     'image_std'				)				)






      def  lowerCamelCase (      self		:  Union[str, Any]				)      ->		List[Any]:
             """simple docstring"""




             _lowerCamelCase :	Tuple						=self.image_processing_class.from_dict(self.image_processor_dict				)
             self.assertEqual(image_processor.size    ,     {'shortest_edge': 20}				)

             _lowerCamelCase :	Tuple						=self.image_processing_class.from_dict(self.image_processor_dict    ,     size=42				)
             self.assertEqual(image_processor.size    ,     {'shortest_edge': 42}				)






      def  lowerCamelCase (      self		:  Optional[Any]				)      ->		int:
             """simple docstring"""




             pass






      def  lowerCamelCase (      self		:  Dict				)      ->		Optional[Any]:
             """simple docstring"""




             _lowerCamelCase :	Optional[Any]						=self.image_processing_class(**self.image_processor_dict				)
             # create random PIL images
             _lowerCamelCase :	Any						=prepare_image_inputs(self.image_processor_tester    ,     equal_resolution=lowercase_				)
             for image in image_inputs:
                    self.assertIsInstance(lowercase_    ,     Image.Image				)

             # Test not batched input
             _lowerCamelCase :	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.size['shortest_edge'],
                     self.image_processor_tester.size['shortest_edge'],
                 )    ,     )

             # Test batched
             _lowerCamelCase :	List[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.size['shortest_edge'],
                     self.image_processor_tester.size['shortest_edge'],
                 )    ,     )






      def  lowerCamelCase (      self		:  int				)      ->		Union[str, Any]:
             """simple docstring"""




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

             # Test not batched input
             _lowerCamelCase :	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.size['shortest_edge'],
                     self.image_processor_tester.size['shortest_edge'],
                 )    ,     )

             # Test batched
             _lowerCamelCase :	Any						=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.size['shortest_edge'],
                     self.image_processor_tester.size['shortest_edge'],
                 )    ,     )






      def  lowerCamelCase (      self		:  str				)      ->		Optional[int]:
             """simple docstring"""




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

             # Test not batched input
             _lowerCamelCase :	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.size['shortest_edge'],
                     self.image_processor_tester.size['shortest_edge'],
                 )    ,     )

             # Test batched
             _lowerCamelCase :	Union[str, Any]						=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.size['shortest_edge'],
                     self.image_processor_tester.size['shortest_edge'],
                 )    ,     )


