




'''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(      __lowercase		,							**__lowercase  ) ->   Union[str, Any]:
     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		,							**_UpperCAmelCase		,							)






class 	lowerCAmelCase_  (					lowerCamelCase__       ):







  '''simple docstring'''

  @staticmethod
  def 				__lowerCAmelCase    (   SCREAMING_SNAKE_CASE_							:       ArgumentParser  ) ->		Union[str, Any]:







       '''simple docstring'''



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



  def __init__(   self							:       Optional[Any]				,     SCREAMING_SNAKE_CASE_							:       str				,     SCREAMING_SNAKE_CASE_							:       str				,     SCREAMING_SNAKE_CASE_							:       str				,     SCREAMING_SNAKE_CASE_							:       str				,     SCREAMING_SNAKE_CASE_							:       str				,     SCREAMING_SNAKE_CASE_							:       bool				,     SCREAMING_SNAKE_CASE_							:       bool				,     SCREAMING_SNAKE_CASE_							:       bool				,     SCREAMING_SNAKE_CASE_							:       bool				,     **SCREAMING_SNAKE_CASE_							:       Optional[int]				,     ) ->		Optional[Any]:







       '''simple docstring'''



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




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

            A:		int        =		Path(SCREAMING_SNAKE_CASE_  ).name + '''.py'''

            A:		Tuple        =		os.path.join(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )
            if os.path.isfile(SCREAMING_SNAKE_CASE_  ):
                 A:		List[str]        =		os.path.dirname(SCREAMING_SNAKE_CASE_  )
            elif os.path.isfile(SCREAMING_SNAKE_CASE_  ):
                 A:		int        =		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:		Dict        =		os.path.join(SCREAMING_SNAKE_CASE_				,     config.DATASETDICT_INFOS_FILENAME  )
            copyfile(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )
            print(f"""Dataset Infos file saved at {user_dataset_infos_path}"""  )












'''simple docstring'''


from collections import OrderedDict
from dataclasses import fields
from typing import Any, Tuple

import numpy as np

from .import_utils import is_torch_available
def 				SCREAMING_SNAKE_CASE(      __lowercase  ) ->   Tuple:
     if is_torch_available():
          import torch

          if isinstance(__lowercase		,							torch.Tensor  ):
               return True

     return isinstance(__lowercase		,							np.ndarray  )






class 	lowerCAmelCase_  (					UpperCAmelCase_       ):







  '''simple docstring'''

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







       '''simple docstring'''



       A:		List[str]        =		fields(self  )

       # Safety and consistency checks
       if not len(SCREAMING_SNAKE_CASE_  ):
            raise ValueError(f"""{self.__class__.__name__} has no fields."""  )

       A:		Optional[Any]        =		getattr(self				,     class_fields[0].name  )
       A:		Any        =		all(getattr(self				,     field.name  ) is None for field in class_fields[1:]  )

       if other_fields_are_none and isinstance(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  ):
            for key, value in first_field.items():
                 A:		Any        =		value
       else:
            for field in class_fields:
                 A:		List[Any]        =		getattr(self				,     field.name  )
                 if v is not None:
                      A:		int        =		v



  def __delitem__(   self							:       Optional[int]				,     *SCREAMING_SNAKE_CASE_							:       Union[str, Any]				,     **SCREAMING_SNAKE_CASE_							:       List[str]  ) ->		List[str]:







       '''simple docstring'''



       raise Exception(f"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""  )



  def 				_snake_case    (   self							:       int				,     *SCREAMING_SNAKE_CASE_							:       Optional[Any]				,     **SCREAMING_SNAKE_CASE_							:       Any  ) ->		str:







       '''simple docstring'''



       raise Exception(f"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance."""  )



  def 				_snake_case    (   self							:       int				,     *SCREAMING_SNAKE_CASE_							:       Dict				,     **SCREAMING_SNAKE_CASE_							:       Any  ) ->		Optional[Any]:







       '''simple docstring'''



       raise Exception(f"""You cannot use ``pop`` on a {self.__class__.__name__} instance."""  )



  def 				_snake_case    (   self							:       int				,     *SCREAMING_SNAKE_CASE_							:       int				,     **SCREAMING_SNAKE_CASE_							:       Optional[Any]  ) ->		int:







       '''simple docstring'''



       raise Exception(f"""You cannot use ``update`` on a {self.__class__.__name__} instance."""  )



  def __getitem__(   self							:       int				,     SCREAMING_SNAKE_CASE_							:       List[Any]  ) ->		Tuple:







       '''simple docstring'''



       if isinstance(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  ):
            A:		Any        =		dict(self.items()  )
            return inner_dict[k]
       else:
            return self.to_tuple()[k]



  def __setattr__(   self							:       Optional[Any]				,     SCREAMING_SNAKE_CASE_							:       Union[str, Any]				,     SCREAMING_SNAKE_CASE_							:       Union[str, Any]  ) ->		Dict:







       '''simple docstring'''



       if name in self.keys() and value is not None:
            # Don't call self.__setitem__ to avoid recursion errors
            super().__setitem__(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )
       super().__setattr__(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )



  def __setitem__(   self							:       Optional[Any]				,     SCREAMING_SNAKE_CASE_							:       Union[str, Any]				,     SCREAMING_SNAKE_CASE_							:       Union[str, Any]  ) ->		int:







       '''simple docstring'''



       super().__setitem__(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )
       # Don't call self.__setattr__ to avoid recursion errors
       super().__setattr__(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )




  def 				_snake_case    (   self							:       Optional[Any]  ) ->		Tuple[Any]:







       '''simple docstring'''



       return tuple(self[k] for k in self.keys()  )






