"""simple docstring"""
import multiprocessing
import os
from typing import BinaryIO, Optional, Union

import fsspec

from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.json.json import Json
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader



class 					lowerCAmelCase_      (     lowerCAmelCase   ):



				"""simple docstring"""

				def __init__(			self						,      lowerCAmelCase						,      lowerCAmelCase = None						,      lowerCAmelCase = None						,      lowerCAmelCase = None						,      lowerCAmelCase = False						,      lowerCAmelCase = False						,      lowerCAmelCase = None						,      lowerCAmelCase = None						,      **lowerCAmelCase						,      ):






										"""simple docstring"""

										super().__init__(
										    lowerCAmelCase						,      split=lowerCAmelCase						,      features=lowerCAmelCase						,      cache_dir=lowerCAmelCase						,      keep_in_memory=lowerCAmelCase						,      streaming=lowerCAmelCase						,      num_proc=lowerCAmelCase						,      **lowerCAmelCase						,      )
										snake_case        =     field
										snake_case        =     path_or_paths if isinstance(lowerCAmelCase						,      lowerCAmelCase      ) else {self.split: path_or_paths}
										snake_case        =     Json(
										    cache_dir=lowerCAmelCase						,      data_files=lowerCAmelCase						,      features=lowerCAmelCase						,      field=lowerCAmelCase						,      **lowerCAmelCase						,      )

				def 						snake_case	(			self      ):






										"""simple docstring"""

										if self.streaming:
																snake_case        =     self.builder.as_streaming_dataset(split=self.split      )
										# Build regular (map-style) dataset
										else:
																snake_case        =     None
																snake_case        =     None
																snake_case        =     None
																snake_case        =     None

																self.builder.download_and_prepare(
																    download_config=lowerCAmelCase						,      download_mode=lowerCAmelCase						,      verification_mode=lowerCAmelCase						,      base_path=lowerCAmelCase						,      num_proc=self.num_proc						,      )
																snake_case        =     self.builder.as_dataset(
																    split=self.split						,      verification_mode=lowerCAmelCase						,      in_memory=self.keep_in_memory      )
										return dataset





class 					lowerCAmelCase_      :



				"""simple docstring"""

				def __init__(			self						,      lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase = None						,      lowerCAmelCase = None						,      **lowerCAmelCase						,      ):






										"""simple docstring"""

										if num_proc is not None and num_proc <= 0:
																raise ValueError(F"""num_proc {num_proc} must be an integer > 0."""      )

										snake_case        =     dataset
										snake_case        =     path_or_buf
										snake_case        =     batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
										snake_case        =     num_proc
										snake_case        =     'utf-8'
										snake_case        =     to_json_kwargs

				def 						snake_case	(			self      ):






										"""simple docstring"""

										snake_case        =     self.to_json_kwargs.pop('path_or_buf'						,      lowerCAmelCase      )
										snake_case        =     self.to_json_kwargs.pop('orient'						,      'records'      )
										snake_case        =     self.to_json_kwargs.pop('lines'						,      True if orient == 'records' else False      )
										snake_case        =     self.to_json_kwargs.pop('index'						,      False if orient in ['split', 'table'] else True      )
										snake_case        =     self.to_json_kwargs.pop('compression'						,      lowerCAmelCase      )

										if compression not in [None, "infer", "gzip", "bz2", "xz"]:
																raise NotImplementedError(F"""`datasets` currently does not support {compression} compression"""      )

										if isinstance(self.path_or_buf						,      (str, bytes, os.PathLike)      ):
																with fsspec.open(self.path_or_buf						,      'wb'						,      compression=lowerCAmelCase      ) as buffer:
																						snake_case        =     self._write(file_obj=lowerCAmelCase						,      orient=lowerCAmelCase						,      lines=lowerCAmelCase						,      index=lowerCAmelCase						,      **self.to_json_kwargs      )
										else:
																if compression:
																						raise NotImplementedError(
																						    F"""The compression parameter is not supported when writing to a buffer, but compression={compression}"""
																						    ' was passed. Please provide a local path instead.'      )
																snake_case        =     self._write(
																    file_obj=self.path_or_buf						,      orient=lowerCAmelCase						,      lines=lowerCAmelCase						,      index=lowerCAmelCase						,      **self.to_json_kwargs      )
										return written

				def 						snake_case	(			self						,      lowerCAmelCase      ):






										"""simple docstring"""

										snake_case   ,snake_case   ,snake_case   ,snake_case   ,snake_case        =     args

										snake_case        =     query_table(
										    table=self.dataset.data						,      key=slice(lowerCAmelCase						,      offset + self.batch_size      )						,      indices=self.dataset._indices						,      )
										snake_case        =     batch.to_pandas().to_json(
										    path_or_buf=lowerCAmelCase						,      orient=lowerCAmelCase						,      lines=lowerCAmelCase						,      index=lowerCAmelCase						,      **lowerCAmelCase      )
										if not json_str.endswith('\n'      ):
																json_str += "\n"
										return json_str.encode(self.encoding      )

				def 						snake_case	(			self						,      lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase						,      **lowerCAmelCase						,      ):






										"""simple docstring"""

										snake_case        =     0

										if self.num_proc is None or self.num_proc == 1:
																for offset in logging.tqdm(
																    range(0						,      len(self.dataset      )						,      self.batch_size      )						,      unit='ba'						,      disable=not logging.is_progress_bar_enabled()						,      desc='Creating json from Arrow format'						,      ):
																						snake_case        =     self._batch_json((offset, orient, lines, index, to_json_kwargs)      )
																						written += file_obj.write(lowerCAmelCase      )
										else:
																snake_case   ,snake_case        =     len(self.dataset      ), self.batch_size
																with multiprocessing.Pool(self.num_proc      ) as pool:
																						for json_str in logging.tqdm(
																						    pool.imap(
																						        self._batch_json						,      [(offset, orient, lines, index, to_json_kwargs) for offset in range(0						,      lowerCAmelCase						,      lowerCAmelCase      )]						,      )						,      total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size						,      unit='ba'						,      disable=not logging.is_progress_bar_enabled()						,      desc='Creating json from Arrow format'						,      ):
																												written += file_obj.write(lowerCAmelCase      )

										return written



"""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


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

if TYPE_CHECKING:
					import pyspark



@dataclass
class 					lowerCAmelCase_      (     datasets.BuilderConfig   ):



				"""simple docstring"""
				_lowerCAmelCase       :      Optional[datasets.Features]     					=  None





def 				lowerCAmelCase__      (     _UpperCamelCase    :			"pyspark.sql.DataFrame"	,     _UpperCamelCase    :			List[int]	,     )   ->			Dict:





						"""simple docstring"""






						import pyspark

						def generate_fn():
												snake_case        =     df.select('*'	,     pyspark.sql.functions.spark_partition_id().alias('part_id'   )   )
												for partition_id in partition_order:
																		snake_case        =     df_with_partition_id.select('*'   ).where(f"""part_id = {partition_id}"""   ).drop('part_id'   )
																		snake_case        =     partition_df.collect()
																		snake_case        =     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						,      lowerCAmelCase						,      lowerCAmelCase=None						,      ):






										"""simple docstring"""

										snake_case        =     df
										snake_case        =     partition_order or range(self.df.rdd.getNumPartitions()      )
										snake_case        =     _generate_iterable_examples(self.df						,      self.partition_order      )

				def __iter__(			self      ):






										"""simple docstring"""

										yield from self.generate_examples_fn()

				def 						snake_case	(			self						,      lowerCAmelCase      ):






										"""simple docstring"""

										snake_case        =     list(range(self.df.rdd.getNumPartitions()      )      )
										generator.shuffle(lowerCAmelCase      )
										return SparkExamplesIterable(self.df						,      partition_order=lowerCAmelCase      )

				def 						snake_case	(			self						,      lowerCAmelCase						,      lowerCAmelCase      ):






										"""simple docstring"""

										snake_case        =     self.split_shard_indices_by_worker(lowerCAmelCase						,      lowerCAmelCase      )
										return SparkExamplesIterable(self.df						,      partition_order=lowerCAmelCase      )

				@property
				def 						snake_case	(			self      ):






										"""simple docstring"""

										return len(self.partition_order      )





class 					lowerCAmelCase_      (     datasets.DatasetBuilder   ):



				"""simple docstring"""
				_lowerCAmelCase       :      List[str]     					=  SparkConfig

				def __init__(			self						,      lowerCAmelCase						,      lowerCAmelCase = None						,      lowerCAmelCase = None						,      **lowerCAmelCase						,      ):






										"""simple docstring"""

										import pyspark

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

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

				def 						snake_case	(			self      ):






										"""simple docstring"""

										def create_cache_and_write_probe(lowerCAmelCase      ):
																# 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=lowerCAmelCase      )
																snake_case        =     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(lowerCAmelCase						,      '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:
																snake_case        =     (
																    self._spark.sparkContext.parallelize(range(1      )						,      1      ).mapPartitions(lowerCAmelCase      ).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 						snake_case	(			self      ):






										"""simple docstring"""

										return datasets.DatasetInfo(features=self.config.features      )

				def 						snake_case	(			self						,      lowerCAmelCase      ):






										"""simple docstring"""

										return [datasets.SplitGenerator(name=datasets.Split.TRAIN      )]

				def 						snake_case	(			self						,      lowerCAmelCase      ):






										"""simple docstring"""

										import pyspark

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

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

				def 						snake_case	(			self						,      lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase						,      ):






										"""simple docstring"""

										import pyspark

										snake_case        =     ParquetWriter if file_format == 'parquet' else ArrowWriter
										snake_case        =     os.path.join(self._working_dir						,      os.path.basename(lowerCAmelCase      )      ) if self._working_dir else fpath
										snake_case        =     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.
										snake_case        =     self.config.features
										snake_case        =     self._writer_batch_size
										snake_case        =     self._fs.storage_options

										def write_arrow(lowerCAmelCase      ):
																# Within the same SparkContext, no two task attempts will share the same attempt ID.
																snake_case        =     pyspark.TaskContext().taskAttemptId()
																snake_case        =     next(lowerCAmelCase						,      lowerCAmelCase      )
																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']						,      )
																snake_case        =     0
																snake_case        =     writer_class(
																    features=lowerCAmelCase						,      path=working_fpath.replace('SSSSS'						,      F"""{shard_id:05d}"""      ).replace('TTTTT'						,      F"""{task_id:05d}"""      )						,      writer_batch_size=lowerCAmelCase						,      storage_options=lowerCAmelCase						,      embed_local_files=lowerCAmelCase						,      )
																snake_case        =     pa.Table.from_batches([first_batch]      )
																writer.write_table(lowerCAmelCase      )
																for batch in it:
																						if max_shard_size is not None and writer._num_bytes >= max_shard_size:
																												snake_case   ,snake_case        =     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
																												snake_case        =     writer_class(
																												    features=writer._features						,      path=working_fpath.replace('SSSSS'						,      F"""{shard_id:05d}"""      ).replace('TTTTT'						,      F"""{task_id:05d}"""      )						,      writer_batch_size=lowerCAmelCase						,      storage_options=lowerCAmelCase						,      embed_local_files=lowerCAmelCase						,      )
																						snake_case        =     pa.Table.from_batches([batch]      )
																						writer.write_table(lowerCAmelCase      )

																if writer._num_bytes > 0:
																						snake_case   ,snake_case        =     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(lowerCAmelCase      )      ):
																												snake_case        =     os.path.join(os.path.dirname(lowerCAmelCase      )						,      os.path.basename(lowerCAmelCase      )      )
																												shutil.move(lowerCAmelCase						,      lowerCAmelCase      )

										snake_case        =     (
										    self.df.mapInArrow(lowerCAmelCase						,      '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 						snake_case	(			self						,      lowerCAmelCase						,      lowerCAmelCase = "arrow"						,      lowerCAmelCase = None						,      lowerCAmelCase = None						,      **lowerCAmelCase						,      ):






										"""simple docstring"""

										self._validate_cache_dir()

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

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

										snake_case        =     0
										snake_case        =     0
										snake_case        =     0
										snake_case        =     []
										snake_case        =     []

										for task_id, content in self._prepare_split_single(lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase      ):
																(
																    (
																    snake_case
																)   ,(
																    snake_case
																)   ,(
																    snake_case
																)   ,(
																    snake_case
																)   ,
																)        =     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(lowerCAmelCase      )

										snake_case        =     total_num_examples
										snake_case        =     total_num_bytes

										# should rename everything at the end
										logger.debug(F"""Renaming {total_shards} shards."""      )
										if total_shards > 1:
																snake_case        =     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.
																snake_case        =     self._fs

																# use the -SSSSS-of-NNNNN pattern
																def _rename_shard(
																    lowerCAmelCase						,      lowerCAmelCase						,      lowerCAmelCase						,      ):
																						rename(
																						    lowerCAmelCase						,      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}"""      )						,      )

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

				def 						snake_case	(			self						,      lowerCAmelCase						,      ):






										"""simple docstring"""

										return SparkExamplesIterable(self.df      )


