


'''simple docstring'''






import copy
import re






class    __snake_case       :







    """simple docstring"""



    lowercase    =					'hp'
    lowercase    =					{}
    lowercase    =					None

    @classmethod
    def __lowercase   (   cls    :  Any    ,						lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  str		)   ->  Optional[Any]:
      lowerCAmelCase_			:      Optional[Any]			=   prefix
      lowerCAmelCase_			:      Optional[Any]			=   defaults
      cls.build_naming_info()

    @staticmethod
    def __lowercase   (   lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  Any		)   ->  List[Any]:
      if len(lowerCamelCase		) == 0:
        return ""
      lowerCAmelCase_			:      Union[str, Any]			=   None
      if any(char.isdigit() for char in word		):
        raise Exception(F'Parameters should not contain numbers: \'{word}\' contains a number'		)
      if word in info["short_word"]:
        return info["short_word"][word]
      for prefix_len in range(1    ,						len(lowerCamelCase		) + 1		):
        lowerCAmelCase_			:      Dict			=   word[:prefix_len]
        if prefix in info["reverse_short_word"]:
          continue
        else:
          lowerCAmelCase_			:      Optional[Any]			=   prefix
          break

      if short_word is None:
        # Paranoid fallback
        def int_to_alphabetic(lowerCamelCase    :  str		):
          lowerCAmelCase_			:      Optional[int]			=   """"""
          while integer != 0:
            lowerCAmelCase_			:      Any			=   chr(ord("""A"""		) + integer % 10		) + s
            integer //= 10
          return s

        lowerCAmelCase_			:      Optional[Any]			=   0
        while True:
          lowerCAmelCase_			:      Union[str, Any]			=   word + """#""" + int_to_alphabetic(lowerCamelCase		)
          if sword in info["reverse_short_word"]:
            continue
          else:
            lowerCAmelCase_			:      List[str]			=   sword
            break

      lowerCAmelCase_			:      int			=   short_word
      lowerCAmelCase_			:      Tuple			=   word
      return short_word

    @staticmethod
    def __lowercase   (   lowerCamelCase    :  Dict    ,						lowerCamelCase    :  int		)   ->  Tuple:
      lowerCAmelCase_			:      List[Any]			=   param_name.split("""_"""		)

      lowerCAmelCase_			:      Any			=   [TrialShortNamer.shortname_for_word(lowerCamelCase    ,						lowerCamelCase		) for word in words]

      # We try to create a separatorless short name, but if there is a collision we have to fallback
      # to a separated short name
      lowerCAmelCase_			:      int			=   ["""""", """_"""]

      for separator in separators:
        lowerCAmelCase_			:      Any			=   separator.join(lowerCamelCase		)
        if shortname not in info["reverse_short_param"]:
          lowerCAmelCase_			:      int			=   shortname
          lowerCAmelCase_			:      Optional[int]			=   param_name
          return shortname

      return param_name

    @staticmethod
    def __lowercase   (   lowerCamelCase    :  int    ,						lowerCamelCase    :  Union[str, Any]		)   ->  int:
      lowerCAmelCase_			:      List[str]			=   TrialShortNamer.shortname_for_key(lowerCamelCase    ,						lowerCamelCase		)
      lowerCAmelCase_			:      List[str]			=   short_name
      lowerCAmelCase_			:      Optional[int]			=   param_name

    @classmethod
    def __lowercase   (   cls    :  List[Any]		)   ->  List[Any]:
      if cls.NAMING_INFO is not None:
        return

      lowerCAmelCase_			:      List[Any]			=   {
          """short_word""": {},
          """reverse_short_word""": {},
          """short_param""": {},
          """reverse_short_param""": {},
      }

      lowerCAmelCase_			:      Optional[int]			=   list(cls.DEFAULTS.keys()		)

      for k in field_keys:
        cls.add_new_param_name(lowerCamelCase    ,						lowerCamelCase		)

      lowerCAmelCase_			:      Optional[int]			=   info

    @classmethod
    def __lowercase   (   cls    :  Dict    ,						lowerCamelCase    :  Optional[Any]		)   ->  Union[str, Any]:
      cls.build_naming_info()
      assert cls.PREFIX is not None
      lowerCAmelCase_			:      List[str]			=   [copy.copy(cls.PREFIX		)]

      for k, v in params.items():
        if k not in cls.DEFAULTS:
          raise Exception(F'You should provide a default value for the param name {k} with value {v}'		)
        if v == cls.DEFAULTS[k]:
          # The default value is not added to the name
          continue

        lowerCAmelCase_			:      Tuple			=   cls.NAMING_INFO["""short_param"""][k]

        if isinstance(lowerCamelCase    ,						lowerCamelCase		):
          lowerCAmelCase_			:      Union[str, Any]			=   1 if v else 0

        lowerCAmelCase_			:      Optional[int]			=   """""" if isinstance(lowerCamelCase    ,						(int, float)		) else """-"""
        lowerCAmelCase_			:      Union[str, Any]			=   F'{key}{sep}{v}'
        name.append(lowerCamelCase		)

      return "_".join(lowerCamelCase		)





    @classmethod
    def __lowercase   (   cls    :  Optional[int]    ,						lowerCamelCase    :  Dict		)   ->  Union[str, Any]:
      lowerCAmelCase_			:      List[Any]			=   repr[len(cls.PREFIX		) + 1 :]
      if repr == "":
        lowerCAmelCase_			:      Dict			=   []
      else:
        lowerCAmelCase_			:      List[Any]			=   repr.split("""_"""		)

      lowerCAmelCase_			:      int			=   {}

      for value in values:
        if "-" in value:
          lowerCAmelCase_,							lowerCAmelCase_			:      str			=   value.split("""-"""		)
        else:
          lowerCAmelCase_			:      Any			=   re.sub("""[0-9.]"""    ,						""""""    ,						lowerCamelCase		)
          lowerCAmelCase_			:      Optional[int]			=   float(re.sub("""[^0-9.]"""    ,						""""""    ,						lowerCamelCase		)		)

        lowerCAmelCase_			:      int			=   cls.NAMING_INFO["""reverse_short_param"""][p_k]

        lowerCAmelCase_			:      Dict			=   p_v

      for k in cls.DEFAULTS:
        if k not in parameters:
          lowerCAmelCase_			:      Union[str, Any]			=   cls.DEFAULTS[k]

      return parameters







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


__A					:  Optional[Any]											=      datasets.utils.logging.get_logger(__name__)

if TYPE_CHECKING:
  import pyspark






@dataclass
class    __snake_case       (   datasets.BuilderConfig):







    """simple docstring"""



    lowercase    =					None







def 				UpperCamelCase_			(    A__					:   "pyspark.sql.DataFrame"							,    A__					:   List[int]							,    ):
  '''simple docstring'''





  import pyspark

  def generate_fn():
    lowerCAmelCase_			:      Union[str, Any]			=   df.select("""*"""							,    pyspark.sql.functions.spark_partition_id().alias("""part_id"""					)					)
    for partition_id in partition_order:
      lowerCAmelCase_			:      int			=   df_with_partition_id.select("""*"""					).where(f'part_id = {partition_id}'					).drop("""part_id"""					)
      lowerCAmelCase_			:      Union[str, Any]			=   partition_df.collect()
      lowerCAmelCase_			:      str			=   0
      for row in rows:
        yield f'{partition_id}_{row_id}', row.asDict()
        row_id += 1

  return generate_fn






class    __snake_case       (   _BaseExamplesIterable):







    """simple docstring"""



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

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

    def __lowercase   (   self    :  Any    ,						lowerCamelCase    :  np.random.Generator		)   ->  "SparkExamplesIterable":
      lowerCAmelCase_			:      Optional[int]			=   list(range(self.df.rdd.getNumPartitions()		)		)
      generator.shuffle(lowerCamelCase		)
      return SparkExamplesIterable(self.df    ,						partition_order=lowerCamelCase		)

    def __lowercase   (   self    :  Optional[Any]    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  int		)   ->  "SparkExamplesIterable":
      lowerCAmelCase_			:      Tuple			=   self.split_shard_indices_by_worker(lowerCamelCase    ,						lowerCamelCase		)
      return SparkExamplesIterable(self.df    ,						partition_order=lowerCamelCase		)





    @property
    def __lowercase   (   self    :  str		)   ->  int:
      return len(self.partition_order		)







class    __snake_case       (   datasets.DatasetBuilder):







    """simple docstring"""



    lowercase    =					SparkConfig

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

      lowerCAmelCase_			:      Dict			=   pyspark.sql.SparkSession.builder.getOrCreate()
      lowerCAmelCase_			:      List[str]			=   df
      lowerCAmelCase_			:      List[Any]			=   working_dir

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

    def __lowercase   (   self    :  Tuple		)   ->  Union[str, Any]:
      # Returns the path of the created file.
      def create_cache_and_write_probe(lowerCamelCase    :  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=lowerCamelCase		)
        lowerCAmelCase_			:      List[str]			=   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:
        lowerCAmelCase_			:      str			=   (
            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 __lowercase   (   self    :  Any		)   ->  List[Any]:
      return datasets.DatasetInfo(features=self.config.features		)

    def __lowercase   (   self    :  str    ,						lowerCamelCase    :  datasets.download.download_manager.DownloadManager		)   ->  Optional[int]:
      return [datasets.SplitGenerator(name=datasets.Split.TRAIN		)]

    def __lowercase   (   self    :  Any    ,						lowerCamelCase    :  Tuple		)   ->  Optional[Any]:
      import pyspark

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

      lowerCAmelCase_			:      str			=   self.df.count()
      lowerCAmelCase_			:      Any			=   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.
      lowerCAmelCase_			:      str			=   (
          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
      )
      lowerCAmelCase_			:      List[Any]			=   approx_bytes_per_row * df_num_rows
      if approx_total_size > max_shard_size:
        # Make sure there is at least one row per partition.
        lowerCAmelCase_			:      Tuple			=   min(lowerCamelCase    ,						int(approx_total_size / max_shard_size		)		)
        lowerCAmelCase_			:      Dict			=   self.df.repartition(lowerCamelCase		)

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

      lowerCAmelCase_			:      List[str]			=   ParquetWriter if file_format == """parquet""" else ArrowWriter
      lowerCAmelCase_			:      int			=   os.path.join(self._working_dir    ,						os.path.basename(lowerCamelCase		)		) if self._working_dir else fpath
      lowerCAmelCase_			:      Tuple			=   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.
      lowerCAmelCase_			:      str			=   self.config.features
      lowerCAmelCase_			:      Tuple			=   self._writer_batch_size
      lowerCAmelCase_			:      Any			=   self._fs.storage_options

      def write_arrow(lowerCamelCase    :  Optional[int]		):
        # Within the same SparkContext, no two task attempts will share the same attempt ID.
        lowerCAmelCase_			:      Union[str, Any]			=   pyspark.TaskContext().taskAttemptId()
        lowerCAmelCase_			:      Union[str, Any]			=   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"""]    ,						)
        lowerCAmelCase_			:      List[Any]			=   0
        lowerCAmelCase_			:      Dict			=   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    ,						)
        lowerCAmelCase_			:      str			=   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:
            lowerCAmelCase_,							lowerCAmelCase_			:      Any			=   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
            lowerCAmelCase_			:      Optional[int]			=   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    ,						)
          lowerCAmelCase_			:      Tuple			=   pa.Table.from_batches([batch]		)
          writer.write_table(lowerCamelCase		)

        if writer._num_bytes > 0:
          lowerCAmelCase_,							lowerCAmelCase_			:      List[str]			=   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		)		):
            lowerCAmelCase_			:      str			=   os.path.join(os.path.dirname(lowerCamelCase		)    ,						os.path.basename(lowerCamelCase		)		)
            shutil.move(lowerCamelCase    ,						lowerCamelCase		)

      lowerCAmelCase_			:      Dict			=   (
          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 __lowercase   (   self    :  Any    ,						lowerCamelCase    :  "datasets.SplitGenerator"    ,						lowerCamelCase    :  str = "arrow"    ,						lowerCamelCase    :  Optional[Union[str, int]] = None    ,						lowerCamelCase    :  Optional[int] = None    ,						**lowerCamelCase    :  List[str]    ,						)   ->  Optional[int]:
      self._validate_cache_dir()

      lowerCAmelCase_			:      List[str]			=   convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE		)
      self._repartition_df_if_needed(lowerCamelCase		)
      lowerCAmelCase_			:      Optional[int]			=   not is_remote_filesystem(self._fs		)
      lowerCAmelCase_			:      Dict			=   os.path.join if is_local else posixpath.join

      lowerCAmelCase_			:      int			=   """-TTTTT-SSSSS-of-NNNNN"""
      lowerCAmelCase_			:      Any			=   F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}'
      lowerCAmelCase_			:      List[str]			=   path_join(self._output_dir    ,						lowerCamelCase		)

      lowerCAmelCase_			:      Dict			=   0
      lowerCAmelCase_			:      int			=   0
      lowerCAmelCase_			:      Dict			=   0
      lowerCAmelCase_			:      Any			=   []
      lowerCAmelCase_			:      Dict			=   []

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

      lowerCAmelCase_			:      Union[str, Any]			=   total_num_examples
      lowerCAmelCase_			:      int			=   total_num_bytes

      # should rename everything at the end
      logger.debug(F'Renaming {total_shards} shards.'		)
      if total_shards > 1:
        lowerCAmelCase_			:      Optional[int]			=   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.
        lowerCAmelCase_			:      List[Any]			=   self._fs

        # use the -SSSSS-of-NNNNN pattern
        def _rename_shard(
            lowerCamelCase    :  int    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  int    ,						):
          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}'		)    ,						)

        lowerCAmelCase_			:      Any			=   []
        lowerCAmelCase_			:      str			=   0
        for i in range(len(lowerCamelCase		)		):
          lowerCAmelCase_,							lowerCAmelCase_			:      Tuple			=   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
        lowerCAmelCase_			:      List[Any]			=   0
        lowerCAmelCase_			:      str			=   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 __lowercase   (   self    :  Dict    ,						lowerCamelCase    :  "datasets.SplitGenerator"    ,						)   ->  SparkExamplesIterable:
      return SparkExamplesIterable(self.df		)



