
"""simple docstring"""


import os
import posixpath
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union

import numpy as np
import pyarrow as pa

import datasets
from datasets.arrow_writer import ArrowWriter, ParquetWriter
from datasets.config import MAX_SHARD_SIZE
from datasets.filesystems import (
    is_remote_filesystem,
    rename,
)
from datasets.iterable_dataset import _BaseExamplesIterable
from datasets.utils.py_utils import convert_file_size_to_int


_lowercase				 =					datasets.utils.logging.get_logger(__name__)

if TYPE_CHECKING:
		import pyspark







@dataclass
class 					lowerCAmelCase_					(   datasets.BuilderConfig     ):



						'''simple docstring'''


						_lowerCamelCase:     Optional[datasets.Features]   =     None






def    _snake_case					(		snake_case__ :  "pyspark.sql.DataFrame"						,   snake_case__ :  List[int]						,   ):
	import pyspark

	def generate_fn():
		A     = df.select('*'						,   pyspark.sql.functions.spark_partition_id().alias('part_id'  )  )
		for partition_id in partition_order:
			A     = df_with_partition_id.select('*'  ).where(F'part_id = {partition_id}'  ).drop('part_id'  )
			A     = partition_df.collect()
			A     = 0
			for row in rows:
				yield F'{partition_id}_{row_id}', row.asDict()
				row_id += 1

	return generate_fn







class 					lowerCAmelCase_					(   _BaseExamplesIterable     ):



						'''simple docstring'''


						def __init__(			self  :   str	,A_  :   "pyspark.sql.DataFrame"	,A_  :   Optional[int]=None	,)  -> str:
							A     = df
							A     = partition_order or range(self.df.rdd.getNumPartitions()   )
							A     = _generate_iterable_examples(self.df	,self.partition_order   )


						def __iter__(			self  :   Dict   )  -> Dict:
							yield from self.generate_examples_fn()


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[str]	,A_  :   np.random.Generator   )  -> "SparkExamplesIterable":
							A     = list(range(self.df.rdd.getNumPartitions()   )   )
							generator.shuffle(A_   )
							return SparkExamplesIterable(self.df	,partition_order=A_   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]	,A_  :   int	,A_  :   int   )  -> "SparkExamplesIterable":
							A     = self.split_shard_indices_by_worker(A_	,A_   )
							return SparkExamplesIterable(self.df	,partition_order=A_   )




						@property
						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[Any]   )  -> int:
							return len(self.partition_order   )







class 					lowerCAmelCase_					(   datasets.DatasetBuilder     ):



						'''simple docstring'''


						_lowerCamelCase:     Any   =     SparkConfig


						def __init__(			self  :   Union[str, Any]	,A_  :   "pyspark.sql.DataFrame"	,A_  :   str = None	,A_  :   str = None	,**A_  :   Union[str, Any]	,)  -> Union[str, Any]:
							import pyspark

							A     = pyspark.sql.SparkSession.builder.getOrCreate()
							A     = df
							A     = working_dir

							super().__init__(
							    cache_dir=A_	,config_name=str(self.df.semanticHash()   )	,**A_	,)


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]   )  -> Optional[Any]:
							# Returns the path of the created file.
							def create_cache_and_write_probe(A_  :   int   ):
								# makedirs with exist_ok will recursively create the directory. It will not throw an error if directories
								# already exist.
								os.makedirs(self._cache_dir	,exist_ok=A_   )
								A     = os.path.join(self._cache_dir	,'fs_test' + uuid.uuida().hex   )
								# Opening the file in append mode will create a new file unless it already exists, in which case it will not
								# change the file contents.
								open(A_	,'a'   )
								return [probe_file]

							if self._spark.conf.get('spark.master'	,''   ).startswith('local'   ):
								return

							# If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS
							# accessible to the driver.
							# TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error.
							if self._cache_dir:
								A     = (
								    self._spark.sparkContext.parallelize(range(1   )	,1   ).mapPartitions(A_   ).collect()
								)
								if os.path.isfile(probe[0]   ):
									return

							raise ValueError(
							    'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir'   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Tuple   )  -> int:
							return datasets.DatasetInfo(features=self.config.features   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   str	,A_  :   datasets.download.download_manager.DownloadManager   )  -> Any:
							return [datasets.SplitGenerator(name=datasets.Split.TRAIN   )]


						def     _SCREAMING_SNAKE_CASE   (			self  :   Tuple	,A_  :   Optional[Any]   )  -> List[str]:
							import pyspark

							def get_arrow_batch_size(A_  :   Tuple   ):
								for batch in it:
									yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]}   )

							A     = self.df.count()
							A     = df_num_rows if df_num_rows <= 100 else 100
							# Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample.
							A     = (
							    self.df.limit(A_   )
							    .repartition(1   )
							    .mapInArrow(A_	,'batch_bytes: long'   )
							    .agg(pyspark.sql.functions.sum('batch_bytes'   ).alias('sample_bytes'   )   )
							    .collect()[0]
							    .sample_bytes
							    / sample_num_rows
							)
							A     = approx_bytes_per_row * df_num_rows
							if approx_total_size > max_shard_size:
								# Make sure there is at least one row per partition.
								A     = min(A_	,int(approx_total_size / max_shard_size   )   )
								A     = self.df.repartition(A_   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]	,A_  :   str	,A_  :   str	,A_  :   int	,)  -> Iterable[Tuple[int, bool, Union[int, tuple]]]:
							import pyspark

							A     = ParquetWriter if file_format == 'parquet' else ArrowWriter
							A     = os.path.join(self._working_dir	,os.path.basename(A_   )   ) if self._working_dir else fpath
							A     = file_format == 'parquet'

							# Define these so that we don't reference self in write_arrow, which will result in a pickling error due to
							# pickling the SparkContext.
							A     = self.config.features
							A     = self._writer_batch_size
							A     = self._fs.storage_options

							def write_arrow(A_  :   List[Any]   ):
								# Within the same SparkContext, no two task attempts will share the same attempt ID.
								A     = pyspark.TaskContext().taskAttemptId()
								A     = next(A_	,A_   )
								if first_batch is None:
									# Some partitions might not receive any data.
									return pa.RecordBatch.from_arrays(
									    [[task_id], [0], [0]]	,names=['task_id', 'num_examples', 'num_bytes']	,)
								A     = 0
								A     = writer_class(
								    features=A_	,path=working_fpath.replace('SSSSS'	,F'{shard_id:05d}'   ).replace('TTTTT'	,F'{task_id:05d}'   )	,writer_batch_size=A_	,storage_options=A_	,embed_local_files=A_	,)
								A     = pa.Table.from_batches([first_batch]   )
								writer.write_table(A_   )
								for batch in it:
									if max_shard_size is not None and writer._num_bytes >= max_shard_size:
										A ,   A     = writer.finalize()
										writer.close()
										yield pa.RecordBatch.from_arrays(
										    [[task_id], [num_examples], [num_bytes]]	,names=['task_id', 'num_examples', 'num_bytes']	,)
										shard_id += 1
										A     = writer_class(
										    features=writer._features	,path=working_fpath.replace('SSSSS'	,F'{shard_id:05d}'   ).replace('TTTTT'	,F'{task_id:05d}'   )	,writer_batch_size=A_	,storage_options=A_	,embed_local_files=A_	,)
									A     = pa.Table.from_batches([batch]   )
									writer.write_table(A_   )

								if writer._num_bytes > 0:
									A ,   A     = writer.finalize()
									writer.close()
									yield pa.RecordBatch.from_arrays(
									    [[task_id], [num_examples], [num_bytes]]	,names=['task_id', 'num_examples', 'num_bytes']	,)

								if working_fpath != fpath:
									for file in os.listdir(os.path.dirname(A_   )   ):
										A     = os.path.join(os.path.dirname(A_   )	,os.path.basename(A_   )   )
										shutil.move(A_	,A_   )

							A     = (
							    self.df.mapInArrow(A_	,'task_id: long, num_examples: long, num_bytes: long'   )
							    .groupBy('task_id'   )
							    .agg(
							        pyspark.sql.functions.sum('num_examples'   ).alias('total_num_examples'   )	,pyspark.sql.functions.sum('num_bytes'   ).alias('total_num_bytes'   )	,pyspark.sql.functions.count('num_bytes'   ).alias('num_shards'   )	,pyspark.sql.functions.collect_list('num_examples'   ).alias('shard_lengths'   )	,)
							    .collect()
							)
							for row in stats:
								yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths)


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[str]	,A_  :   "datasets.SplitGenerator"	,A_  :   str = "arrow"	,A_  :   Optional[Union[str, int]] = None	,A_  :   Optional[int] = None	,**A_  :   List[str]	,)  -> Union[str, Any]:
							self._validate_cache_dir()

							A     = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE   )
							self._repartition_df_if_needed(A_   )
							A     = not is_remote_filesystem(self._fs   )
							A     = os.path.join if is_local else posixpath.join

							A     = '-TTTTT-SSSSS-of-NNNNN'
							A     = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}'
							A     = path_join(self._output_dir	,A_   )

							A     = 0
							A     = 0
							A     = 0
							A     = []
							A     = []

							for task_id, content in self._prepare_split_single(A_	,A_	,A_   ):
								(
								    (
								    A
								) ,   (
								    A
								) ,   (
								    A
								) ,   (
								    A
								) ,   
								)     = content
								if num_bytes > 0:
									total_num_examples += num_examples
									total_num_bytes += num_bytes
									total_shards += num_shards
									task_id_and_num_shards.append((task_id, num_shards)   )
									all_shard_lengths.extend(A_   )

							A     = total_num_examples
							A     = total_num_bytes

							# should rename everything at the end
							logger.debug(F'Renaming {total_shards} shards.'   )
							if total_shards > 1:
								A     = all_shard_lengths

								# Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a
								# pickling error due to pickling the SparkContext.
								A     = self._fs

								# use the -SSSSS-of-NNNNN pattern
								def _rename_shard(
								    A_  :   int	,A_  :   int	,A_  :   int	,):
									rename(
									    A_	,fpath.replace('SSSSS'	,F'{shard_id:05d}'   ).replace('TTTTT'	,F'{task_id:05d}'   )	,fpath.replace('TTTTT-SSSSS'	,F'{global_shard_id:05d}'   ).replace('NNNNN'	,F'{total_shards:05d}'   )	,)

								A     = []
								A     = 0
								for i in range(len(A_   )   ):
									A ,   A     = task_id_and_num_shards[i]
									for shard_id in range(A_   ):
										args.append([task_id, shard_id, global_shard_id]   )
										global_shard_id += 1
								self._spark.sparkContext.parallelize(A_	,len(A_   )   ).map(lambda A_   : _rename_shard(*A_   )   ).collect()
							else:
								# don't use any pattern
								A     = 0
								A     = task_id_and_num_shards[0][0]
								self._rename(
								    fpath.replace('SSSSS'	,F'{shard_id:05d}'   ).replace('TTTTT'	,F'{task_id:05d}'   )	,fpath.replace(A_	,''   )	,)




						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]	,A_  :   "datasets.SplitGenerator"	,)  -> SparkExamplesIterable:
							return SparkExamplesIterable(self.df   )

"""simple docstring"""


# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os

from accelerate.utils import ComputeEnvironment

from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file  # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment  # noqa: F401
from .sagemaker import get_sagemaker_input


_lowercase				 =					'''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine'''






def    _snake_case					(		):
	A     = _ask_options(
	    'In which compute environment are you running?'						,   ['This machine', 'AWS (Amazon SageMaker)']						,   _convert_compute_environment						,   )
	if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
		A     = get_sagemaker_input()
	else:
		A     = get_cluster_input()
	return config






def    _snake_case					(		snake_case__ :  Any=None  ):
	if subparsers is not None:
		A     = subparsers.add_parser('config'						,   description=snake_case__  )
	else:
		A     = argparse.ArgumentParser('Accelerate config command'						,   description=snake_case__  )

	parser.add_argument(
	    '--config_file'						,   default=snake_case__						,   help=(
	        'The path to use to store the config file. Will default to a file named default_config.yaml in the cache '
	        'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '
	        'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '
	        'with \'huggingface\'.'
	    )						,   )

	if subparsers is not None:
		parser.set_defaults(func=snake_case__  )
	return parser






def    _snake_case					(		snake_case__ :  Tuple  ):
	A     = get_user_input()
	if args.config_file is not None:
		A     = args.config_file
	else:
		if not os.path.isdir(snake_case__  ):
			os.makedirs(snake_case__  )
		A     = default_yaml_config_file

	if config_file.endswith('.json'  ):
		config.to_json_file(snake_case__  )
	else:
		config.to_yaml_file(snake_case__  )
	print(F'accelerate configuration saved at {config_file}'  )






def    _snake_case					(		):
	A     = config_command_parser()
	A     = parser.parse_args()
	config_command(snake_case__  )


if __name__ == "__main__":
		main()