


'''simple docstring'''






import json
from typing import Dict, List, Optional, Tuple, Union

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_led import LEDTokenizer


__A					:  Optional[int]											=      logging.get_logger(__name__)


__A					:  Union[str, Any]											=      {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}

__A					:  List[str]											=      {
    "vocab_file": {
        "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json",
    },
    "merges_file": {
        "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt",
    },
    "tokenizer_file": {
        "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json",
    },
}

__A					:  Optional[Any]											=      {
    "allenai/led-base-16384": 1_6384,
}






class    __snake_case       (   _SCREAMING_SNAKE_CASE):







    """simple docstring"""



    lowercase    =					VOCAB_FILES_NAMES
    lowercase    =					PRETRAINED_VOCAB_FILES_MAP
    lowercase    =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    lowercase    =					LEDTokenizer
    lowercase    =					['input_ids', 'attention_mask']

    def __init__(   self    :  Optional[Any]    ,						lowerCamelCase    :  List[Any]=None    ,						lowerCamelCase    :  str=None    ,						lowerCamelCase    :  str=None    ,						lowerCamelCase    :  List[str]="replace"    ,						lowerCamelCase    :  int="<s>"    ,						lowerCamelCase    :  Tuple="</s>"    ,						lowerCamelCase    :  Optional[int]="</s>"    ,						lowerCamelCase    :  Optional[int]="<s>"    ,						lowerCamelCase    :  Dict="<unk>"    ,						lowerCamelCase    :  List[str]="<pad>"    ,						lowerCamelCase    :  Optional[Any]="<mask>"    ,						lowerCamelCase    :  Optional[Any]=False    ,						lowerCamelCase    :  Tuple=True    ,						**lowerCamelCase    :  Any    ,						)   ->  Any:
      super().__init__(
          lowerCamelCase    ,						lowerCamelCase    ,						tokenizer_file=lowerCamelCase    ,						errors=lowerCamelCase    ,						bos_token=lowerCamelCase    ,						eos_token=lowerCamelCase    ,						sep_token=lowerCamelCase    ,						cls_token=lowerCamelCase    ,						unk_token=lowerCamelCase    ,						pad_token=lowerCamelCase    ,						mask_token=lowerCamelCase    ,						add_prefix_space=lowerCamelCase    ,						trim_offsets=lowerCamelCase    ,						**lowerCamelCase    ,						)

      lowerCAmelCase_			:      Optional[Any]			=   json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()		)
      if pre_tok_state.get("""add_prefix_space"""    ,						lowerCamelCase		) != add_prefix_space:
        lowerCAmelCase_			:      Union[str, Any]			=   getattr(lowerCamelCase    ,						pre_tok_state.pop("""type"""		)		)
        lowerCAmelCase_			:      str			=   add_prefix_space
        lowerCAmelCase_			:      Any			=   pre_tok_class(**lowerCamelCase		)

      lowerCAmelCase_			:      Union[str, Any]			=   add_prefix_space

      # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
      lowerCAmelCase_			:      Optional[int]			=   """post_processor"""
      lowerCAmelCase_			:      Union[str, Any]			=   getattr(self.backend_tokenizer    ,						lowerCamelCase    ,						lowerCamelCase		)
      if tokenizer_component_instance:
        lowerCAmelCase_			:      str			=   json.loads(tokenizer_component_instance.__getstate__()		)

        # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
        if "sep" in state:
          lowerCAmelCase_			:      List[Any]			=   tuple(state["""sep"""]		)
        if "cls" in state:
          lowerCAmelCase_			:      Any			=   tuple(state["""cls"""]		)

        lowerCAmelCase_			:      Tuple			=   False

        if state.get("""add_prefix_space"""    ,						lowerCamelCase		) != add_prefix_space:
          lowerCAmelCase_			:      str			=   add_prefix_space
          lowerCAmelCase_			:      Tuple			=   True

        if state.get("""trim_offsets"""    ,						lowerCamelCase		) != trim_offsets:
          lowerCAmelCase_			:      List[Any]			=   trim_offsets
          lowerCAmelCase_			:      int			=   True

        if changes_to_apply:
          lowerCAmelCase_			:      int			=   getattr(lowerCamelCase    ,						state.pop("""type"""		)		)
          lowerCAmelCase_			:      Union[str, Any]			=   component_class(**lowerCamelCase		)
          setattr(self.backend_tokenizer    ,						lowerCamelCase    ,						lowerCamelCase		)

    @property
    # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED
    def __lowercase   (   self    :  Optional[int]		)   ->  str:
      if self._mask_token is None:
        if self.verbose:
          logger.error("""Using mask_token, but it is not set yet."""		)
        return None
      return str(self._mask_token		)

    @mask_token.setter
    def __lowercase   (   self    :  Optional[Any]    ,						lowerCamelCase    :  List[str]		)   ->  Optional[Any]:
      lowerCAmelCase_			:      Optional[Any]			=   AddedToken(lowerCamelCase    ,						lstrip=lowerCamelCase    ,						rstrip=lowerCamelCase		) if isinstance(lowerCamelCase    ,						lowerCamelCase		) else value
      lowerCAmelCase_			:      Optional[int]			=   value

    def __lowercase   (   self    :  List[Any]    ,						*lowerCamelCase    :  List[Any]    ,						**lowerCamelCase    :  Any		)   ->  BatchEncoding:
      lowerCAmelCase_			:      Union[str, Any]			=   kwargs.get("""is_split_into_words"""    ,						lowerCamelCase		)

      if is_split_into_words and not self.add_prefix_space:
        raise ValueError(
            F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
            """to use it with pretokenized inputs."""		)

      return super()._batch_encode_plus(*lowerCamelCase    ,						**lowerCamelCase		)

    def __lowercase   (   self    :  str    ,						*lowerCamelCase    :  List[Any]    ,						**lowerCamelCase    :  Any		)   ->  BatchEncoding:
      lowerCAmelCase_			:      Any			=   kwargs.get("""is_split_into_words"""    ,						lowerCamelCase		)

      if is_split_into_words and not self.add_prefix_space:
        raise ValueError(
            F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
            """to use it with pretokenized inputs."""		)

      return super()._encode_plus(*lowerCamelCase    ,						**lowerCamelCase		)

    def __lowercase   (   self    :  str    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Optional[str] = None		)   ->  Tuple[str]:
      lowerCAmelCase_			:      List[str]			=   self._tokenizer.model.save(lowerCamelCase    ,						name=lowerCamelCase		)
      return tuple(lowerCamelCase		)

    def __lowercase   (   self    :  List[Any]    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  Optional[Any]=None		)   ->  Union[str, Any]:
      lowerCAmelCase_			:      Dict			=   [self.bos_token_id] + token_ids_a + [self.eos_token_id]
      if token_ids_a is None:
        return output

      return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]

    def __lowercase   (   self    :  Tuple    ,						lowerCamelCase    :  List[int]    ,						lowerCamelCase    :  Optional[List[int]] = None		)   ->  List[int]:
      lowerCAmelCase_			:      Union[str, Any]			=   [self.sep_token_id]
      lowerCAmelCase_			:      Optional[int]			=   [self.cls_token_id]

      if token_ids_a is None:
        return len(cls + token_ids_a + sep		) * [0]
      return len(cls + token_ids_a + sep + sep + token_ids_a + sep		) * [0]





    def __lowercase   (   self    :  List[Any]    ,						lowerCamelCase    :  Union[Dict[str, EncodedInput], BatchEncoding]    ,						lowerCamelCase    :  Optional[int] = None    ,						lowerCamelCase    :  PaddingStrategy = PaddingStrategy.DO_NOT_PAD    ,						lowerCamelCase    :  Optional[int] = None    ,						lowerCamelCase    :  Optional[bool] = None    ,						)   ->  dict:
      lowerCAmelCase_			:      Union[str, Any]			=   super()._pad(
          encoded_inputs=lowerCamelCase    ,						max_length=lowerCamelCase    ,						padding_strategy=lowerCamelCase    ,						pad_to_multiple_of=lowerCamelCase    ,						return_attention_mask=lowerCamelCase    ,						)

      # Load from model defaults
      if return_attention_mask is None:
        lowerCAmelCase_			:      List[str]			=   """attention_mask""" in self.model_input_names

      if return_attention_mask and "global_attention_mask" in encoded_inputs:
        lowerCAmelCase_			:      Dict			=   encoded_inputs[self.model_input_names[0]]
        # `global_attention_mask` need to have the same length as other (sequential) inputs.
        lowerCAmelCase_			:      List[str]			=   len(encoded_inputs["""global_attention_mask"""]		) != len(lowerCamelCase		)

        if needs_to_be_padded:
          lowerCAmelCase_			:      Tuple			=   len(lowerCamelCase		) - len(encoded_inputs["""global_attention_mask"""]		)

          if self.padding_side == "right":
            # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
            lowerCAmelCase_			:      Dict			=   (
                encoded_inputs["""global_attention_mask"""] + [-1] * difference
            )
          elif self.padding_side == "left":
            lowerCAmelCase_			:      List[str]			=   [-1] * difference + encoded_inputs[
                """global_attention_mask"""
            ]
          else:
            raise ValueError("""Invalid padding strategy:""" + str(self.padding_side		)		)

      return encoded_inputs







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



