



'''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(      UpperCAmelCase_      :	List[str]					, **UpperCAmelCase_      :	Optional[int]						) ->							str:
							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					, **lowercase_					, )






class      lowerCamelCase__     (     UpperCAmelCase_				):






	'''simple docstring'''

	@staticmethod
	def      lowercase__							(  __A		:  List[str]					)     ->			Any:




								'''simple docstring'''





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




	def __init__(  self		:  str   ,		__A		:  Optional[int]   ,		__A		:  int   ,		__A		:  Union[str, Any]   ,		__A		:  Dict   ,		__A		:  Optional[int]   ,		__A		:  str   ,		__A		:  Tuple   ,		__A		:  Tuple   ,		__A		:  Dict   ,		**__A		:  int   ,		)     ->			Union[str, Any]:




								'''simple docstring'''





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




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

															lowerCAmelCase__  =   Path(__UpperCamelCase					).name + """.py"""

															lowerCAmelCase__  =   os.path.join(__UpperCamelCase   ,		__UpperCamelCase					)
															if os.path.isfile(__UpperCamelCase					):
																						lowerCAmelCase__  =   os.path.dirname(__UpperCamelCase					)
															elif os.path.isfile(__UpperCamelCase					):
																						lowerCAmelCase__  =   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__  =   os.path.join(__UpperCamelCase   ,		config.DATASETDICT_INFOS_FILENAME					)
															copyfile(__UpperCamelCase   ,		__UpperCamelCase					)
															print(f'''Dataset Infos file saved at {user_dataset_infos_path}'''					)











'''simple docstring'''







import subprocess
from argparse import ArgumentParser
from typing import List, Union

from huggingface_hub.hf_api import HfFolder, create_repo, whoami
from requests.exceptions import HTTPError

from . import BaseTransformersCLICommand





class 	lowerCamelCase_				(			UpperCAmelCase_				):




					'''simple docstring'''






					@staticmethod
					def 							__SCREAMING_SNAKE_CASE      (       __UpperCamelCase					):
							_snake_case      			=			parser.add_parser("login",    help="Log in using the same credentials as on huggingface.co"					)
							login_parser.set_defaults(func=lambda __UpperCamelCase					: LoginCommand(__UpperCamelCase					)					)
							_snake_case      			=			parser.add_parser("whoami",    help="Find out which huggingface.co account you are logged in as."					)
							whoami_parser.set_defaults(func=lambda __UpperCamelCase					: WhoamiCommand(__UpperCamelCase					)					)
							_snake_case      			=			parser.add_parser("logout",    help="Log out"					)
							logout_parser.set_defaults(func=lambda __UpperCamelCase					: LogoutCommand(__UpperCamelCase					)					)

							# new system: git-based repo system
							_snake_case      			=			parser.add_parser(
							    "repo",    help="Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos.",    )
							_snake_case      			=			repo_parser.add_subparsers(
							    help="Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands"					)
							_snake_case      			=			repo_subparsers.add_parser(
							    "create",    help="Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co"					)
							repo_create_parser.add_argument(
							    "name",    type=__UpperCamelCase,    help="Name for your model's repo. Will be namespaced under your username to build the model id.",    )
							repo_create_parser.add_argument("--organization",    type=__UpperCamelCase,    help="Optional: organization namespace."					)
							repo_create_parser.add_argument("-y",    "--yes",    action="store_true",    help="Optional: answer Yes to the prompt"					)
							repo_create_parser.set_defaults(func=lambda __UpperCamelCase					: RepoCreateCommand(__UpperCamelCase					)					)





class 	lowerCamelCase_				:




					'''simple docstring'''






					lowercase__       =					"""\u001b[1m"""
					lowercase__       =					"""\u001b[31m"""
					lowercase__       =					"""\u001b[90m"""
					lowercase__       =					"""\u001b[0m"""






					@classmethod
					def 							__SCREAMING_SNAKE_CASE      (       cls,    __UpperCamelCase					):
							return f'''{cls._bold}{s}{cls._reset}'''






					@classmethod
					def 							__SCREAMING_SNAKE_CASE      (       cls,    __UpperCamelCase					):
							return f'''{cls._bold}{cls._red}{s}{cls._reset}'''






					@classmethod
					def 							__SCREAMING_SNAKE_CASE      (       cls,    __UpperCamelCase					):
							return f'''{cls._gray}{s}{cls._reset}'''






def 						_lowercase						(      lowercase_		,				lowercase_    ):



		'''simple docstring'''







		_snake_case      			=			[max(len(str(lowercase_    )    ) for x in col    ) for col in zip(*lowercase_		,				lowercase_    )]
		_snake_case      			=			("{{:{}}} " * len(lowercase_    )).format(*lowercase_    )
		_snake_case      			=			[]
		lines.append(row_format.format(*lowercase_    )    )
		lines.append(row_format.format(*["-" * w for w in col_widths]    )    )
		for row in rows:
				lines.append(row_format.format(*lowercase_    )    )
		return "\n".join(lowercase_    )





class 	lowerCamelCase_				:




					'''simple docstring'''






					def __init__(       self,    __UpperCamelCase					):
							_snake_case      			=			args





class 	lowerCamelCase_				(			UpperCAmelCase_				):




					'''simple docstring'''






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							print(
							    ANSI.red(
							        "ERROR! `huggingface-cli login` uses an outdated login mechanism "
							        "that is not compatible with the Hugging Face Hub backend anymore. "
							        "Please use `huggingface-cli login instead."					)					)





class 	lowerCamelCase_				(			UpperCAmelCase_				):




					'''simple docstring'''






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							print(
							    ANSI.red(
							        "WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use "
							        "`huggingface-cli whoami` instead."					)					)
							_snake_case      			=			HfFolder.get_token()
							if token is None:
									print("Not logged in"					)
									exit()
							try:
									_snake_case			,       _snake_case      			=			whoami(__UpperCamelCase					)
									print(__UpperCamelCase					)
									if orgs:
											print(ANSI.bold("orgs: "					),    ",".join(__UpperCamelCase					)					)
							except HTTPError as e:
									print(__UpperCamelCase					)
									print(ANSI.red(e.response.text					)					)
									exit(1					)





class 	lowerCamelCase_				(			UpperCAmelCase_				):




					'''simple docstring'''






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							print(
							    ANSI.red(
							        "ERROR! `transformers-cli logout` uses an outdated logout mechanism "
							        "that is not compatible with the Hugging Face Hub backend anymore. "
							        "Please use `huggingface-cli logout instead."					)					)





class 	lowerCamelCase_				(			UpperCAmelCase_				):




					'''simple docstring'''






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							print(
							    ANSI.red(
							        "WARNING! Managing repositories through transformers-cli is deprecated. "
							        "Please use `huggingface-cli` instead."					)					)
							_snake_case      			=			HfFolder.get_token()
							if token is None:
									print("Not logged in"					)
									exit(1					)
							try:
									_snake_case      			=			subprocess.check_output(["git", "--version"]					).decode("utf-8"					)
									print(ANSI.gray(stdout.strip()					)					)
							except FileNotFoundError:
									print("Looks like you do not have git installed, please install."					)

							try:
									_snake_case      			=			subprocess.check_output(["git-lfs", "--version"]					).decode("utf-8"					)
									print(ANSI.gray(stdout.strip()					)					)
							except FileNotFoundError:
									print(
									    ANSI.red(
									        "Looks like you do not have git-lfs installed, please install."
									        " You can install from https://git-lfs.github.com/."
									        " Then run `git lfs install` (you only have to do this once)."					)					)
							print(""					)

							_snake_case			,       _snake_case      			=			whoami(__UpperCamelCase					)
							_snake_case      			=			self.args.organization if self.args.organization is not None else user
							_snake_case      			=			f'''{namespace}/{self.args.name}'''
							print(f'''You are about to create {ANSI.bold(__UpperCamelCase					)}'''					)

							if not self.args.yes:
									_snake_case      			=			input("Proceed? [Y/n] "					).lower()
									if not (choice == "" or choice == "y" or choice == "yes"):
											print("Abort"					)
											exit()
							try:
									_snake_case      			=			create_repo(__UpperCamelCase,    name=self.args.name,    organization=self.args.organization					)
							except HTTPError as e:
									print(__UpperCamelCase					)
									print(ANSI.red(e.response.text					)					)
									exit(1					)
							print("\nYour repo now lives at:"					)
							print(f'''  {ANSI.bold(__UpperCamelCase					)}'''					)
							print("\nYou can clone it locally with the command below, and commit/push as usual."					)
							print(f'''\n  git clone {url}'''					)
							print(""					)





