




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


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

if TYPE_CHECKING:
		import pyspark






@dataclass
class 		_lowerCAmelCase       (							datasets.BuilderConfig	):
			"""simple docstring"""
			lowerCAmelCase__           =None







def 	lowercase_		(     SCREAMING_SNAKE_CASE						:		str						,						SCREAMING_SNAKE_CASE						:		List[str]						,						):






	"""simple docstring"""
	import pyspark

	def generate_fn():
		snake_case__						:     Optional[Any]		=df.select('''*'''						,						pyspark.sql.functions.spark_partition_id().alias('''part_id''' ) )
		for partition_id in partition_order:
			snake_case__						:     Optional[Any]		=df_with_partition_id.select('''*''' ).where(F'''part_id = {partition_id}''' ).drop('''part_id''' )
			snake_case__						:     List[str]		=partition_df.collect()
			snake_case__						:     Dict		=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     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE=None     ,		)		->							Optional[Any]:





				"""simple docstring"""







				snake_case__						:     Optional[int]		=df
				snake_case__						:     Dict		=partition_order or range(self.df.rdd.getNumPartitions()       )
				snake_case__						:     str		=_generate_iterable_examples(self.df     ,		self.partition_order       )
			def __iter__(					self       )		->							List[Any]:





				"""simple docstring"""







				yield from self.generate_examples_fn()
			def 					UpperCAmelCase     (					self     ,		__SCREAMING_SNAKE_CASE       )		->							Dict:





				"""simple docstring"""







				snake_case__						:     int		=list(range(self.df.rdd.getNumPartitions()       )       )
				generator.shuffle(lowerCamelCase_       )
				return SparkExamplesIterable(self.df     ,		partition_order=lowerCamelCase_       )
			def 					UpperCAmelCase     (					self     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE       )		->							Optional[Any]:





				"""simple docstring"""







				snake_case__						:     Dict		=self.split_shard_indices_by_worker(lowerCamelCase_     ,		lowerCamelCase_       )
				return SparkExamplesIterable(self.df     ,		partition_order=lowerCamelCase_       )


			@property
			def 					UpperCAmelCase     (					self       )		->							Tuple:





				"""simple docstring"""







				return len(self.partition_order       )






class 		_lowerCAmelCase       (							datasets.DatasetBuilder	):
			"""simple docstring"""
			lowerCAmelCase__           =SparkConfig
			def __init__(					self     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE = None     ,		__SCREAMING_SNAKE_CASE = None     ,		**__SCREAMING_SNAKE_CASE     ,		)		->							Optional[Any]:





				"""simple docstring"""







				import pyspark

				snake_case__						:     Optional[int]		=pyspark.sql.SparkSession.builder.getOrCreate()
				snake_case__						:     Tuple		=df
				snake_case__						:     List[str]		=working_dir

				super().__init__(
				    cache_dir=lowerCamelCase_     ,		config_name=str(self.df.semanticHash()       )     ,		**lowerCamelCase_     ,		)
			def 					UpperCAmelCase     (					self       )		->							Union[str, Any]:





				"""simple docstring"""







				def create_cache_and_write_probe(__SCREAMING_SNAKE_CASE       ):
					# 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__						:     Optional[int]		=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__						:     List[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 					UpperCAmelCase     (					self       )		->							Tuple:





				"""simple docstring"""







				return datasets.DatasetInfo(features=self.config.features       )
			def 					UpperCAmelCase     (					self     ,		__SCREAMING_SNAKE_CASE       )		->							List[str]:





				"""simple docstring"""







				return [datasets.SplitGenerator(name=datasets.Split.TRAIN       )]
			def 					UpperCAmelCase     (					self     ,		__SCREAMING_SNAKE_CASE       )		->							int:





				"""simple docstring"""







				import pyspark

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

				snake_case__						:     List[Any]		=self.df.count()
				snake_case__						:     List[str]		=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.
				snake_case__						:     Optional[int]		=(
				    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__						:     str		=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__						:     int		=min(lowerCamelCase_     ,		int(approx_total_size / max_shard_size       )       )
					snake_case__						:     Optional[int]		=self.df.repartition(lowerCamelCase_       )
			def 					UpperCAmelCase     (					self     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		)		->							List[Any]:





				"""simple docstring"""







				import pyspark

				snake_case__						:     List[Any]		=ParquetWriter if file_format == '''parquet''' else ArrowWriter
				snake_case__						:     str		=os.path.join(self._working_dir     ,		os.path.basename(lowerCamelCase_       )       ) if self._working_dir else fpath
				snake_case__						:     Dict		=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__						:     Any		=self.config.features
				snake_case__						:     str		=self._writer_batch_size
				snake_case__						:     Optional[int]		=self._fs.storage_options

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

					if writer._num_bytes > 0:
						snake_case__,    snake_case__						:     int		=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__						:     List[Any]		=os.path.join(os.path.dirname(lowerCamelCase_       )     ,		os.path.basename(lowerCamelCase_       )       )
							shutil.move(lowerCamelCase_     ,		lowerCamelCase_       )

				snake_case__						:     int		=(
				    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 					UpperCAmelCase     (					self     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE = "arrow"     ,		__SCREAMING_SNAKE_CASE = None     ,		__SCREAMING_SNAKE_CASE = None     ,		**__SCREAMING_SNAKE_CASE     ,		)		->							List[Any]:





				"""simple docstring"""







				self._validate_cache_dir()

				snake_case__						:     int		=convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE       )
				self._repartition_df_if_needed(lowerCamelCase_       )
				snake_case__						:     Optional[int]		=not is_remote_filesystem(self._fs       )
				snake_case__						:     Tuple		=os.path.join if is_local else posixpath.join

				snake_case__						:     Any		='''-TTTTT-SSSSS-of-NNNNN'''
				snake_case__						:     Tuple		=f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}'''
				snake_case__						:     str		=path_join(self._output_dir     ,		lowerCamelCase_       )

				snake_case__						:     Union[str, Any]		=0
				snake_case__						:     List[Any]		=0
				snake_case__						:     int		=0
				snake_case__						:     List[str]		=[]
				snake_case__						:     Optional[int]		=[]

				for task_id, content in self._prepare_split_single(lowerCamelCase_     ,		lowerCamelCase_     ,		lowerCamelCase_       ):
					(
					    (
					    snake_case__     
					),    (
					    snake_case__     
					),    (
					    snake_case__     
					),    (
					    snake_case__     
					),         
					)						:     Union[str, Any]		=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__						:     str		=total_num_examples
				snake_case__						:     Optional[Any]		=total_num_bytes

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

					# use the -SSSSS-of-NNNNN pattern
					def _rename_shard(
					    __SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		):
						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__						:     str		=[]
					snake_case__						:     int		=0
					for i in range(len(lowerCamelCase_       )       ):
						snake_case__,    snake_case__						:     Any		=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 __SCREAMING_SNAKE_CASE       : _rename_shard(*lowerCamelCase_       )       ).collect()
				else:
					# don't use any pattern
					snake_case__						:     int		=0
					snake_case__						:     Any		=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 					UpperCAmelCase     (					self     ,		__SCREAMING_SNAKE_CASE     ,		)		->							Optional[int]:





				"""simple docstring"""







				return SparkExamplesIterable(self.df       )





import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


_SCREAMING_SNAKE_CASE 		=      get_tests_dir("""fixtures""")
_SCREAMING_SNAKE_CASE 		=      get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
_SCREAMING_SNAKE_CASE 		=      get_tests_dir("""fixtures/dummy-config.json""")
class SCREAMING_SNAKE_CASE_		(      unittest.TestCase		):







   def 						lowerCamelCase_	(     self						:						Tuple				):





    """simple docstring"""


    UpperCamelCase			  =      0







   def 						lowerCamelCase_	(     self						:						int				):





    """simple docstring"""


    UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h"""				)
    self.assertIsInstance(lowerCamelCase_   ,   lowerCamelCase_				)







   def 						lowerCamelCase_	(     self						:						Optional[Any]				):





    """simple docstring"""


    UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(lowerCamelCase_				)
    self.assertIsInstance(lowerCamelCase_   ,   lowerCamelCase_				)







   def 						lowerCamelCase_	(     self						:						Tuple				):





    """simple docstring"""


    with tempfile.TemporaryDirectory() as tmpdirname:
     UpperCamelCase			  =      WavaVecaConfig()

     # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(lowerCamelCase_				).to_dict()

     config_dict.pop("""feature_extractor_type"""				)
     UpperCamelCase			  =      WavaVecaFeatureExtractor(**lowerCamelCase_				)

     # save in new folder
     model_config.save_pretrained(lowerCamelCase_				)
     config.save_pretrained(lowerCamelCase_				)

     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(lowerCamelCase_				)

     # make sure private variable is not incorrectly saved
     UpperCamelCase			  =      json.loads(config.to_json_string()				)
     self.assertTrue("""_processor_class""" not in dict_as_saved				)

    self.assertIsInstance(lowerCamelCase_   ,   lowerCamelCase_				)







   def 						lowerCamelCase_	(     self						:						List[str]				):





    """simple docstring"""


    UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(lowerCamelCase_				)
    self.assertIsInstance(lowerCamelCase_   ,   lowerCamelCase_				)







   def 						lowerCamelCase_	(     self						:						int				):





    """simple docstring"""


    with self.assertRaisesRegex(
        lowerCamelCase_   ,   """bert-base is not a local folder and is not a valid model identifier"""				):
     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained("""bert-base"""				)







   def 						lowerCamelCase_	(     self						:						str				):





    """simple docstring"""


    with self.assertRaisesRegex(
        lowerCamelCase_   ,   R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""				):
     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(lowerCamelCase_   ,   revision="""aaaaaa"""				)







   def 						lowerCamelCase_	(     self						:						Any				):





    """simple docstring"""


    with self.assertRaisesRegex(
        lowerCamelCase_   ,   """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""   ,   ):
     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model"""				)







   def 						lowerCamelCase_	(     self						:						List[Any]				):





    """simple docstring"""


    with self.assertRaises(lowerCamelCase_				):
     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(
         """hf-internal-testing/test_dynamic_feature_extractor"""				)
    # If remote code is disabled, we can't load this config.
    with self.assertRaises(lowerCamelCase_				):
     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(
         """hf-internal-testing/test_dynamic_feature_extractor"""   ,   trust_remote_code=lowerCamelCase_				)

    UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(
        """hf-internal-testing/test_dynamic_feature_extractor"""   ,   trust_remote_code=lowerCamelCase_				)
    self.assertEqual(feature_extractor.__class__.__name__   ,   """NewFeatureExtractor"""				)

    # Test feature extractor can be reloaded.
    with tempfile.TemporaryDirectory() as tmp_dir:
     feature_extractor.save_pretrained(lowerCamelCase_				)
     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(lowerCamelCase_   ,   trust_remote_code=lowerCamelCase_				)
    self.assertEqual(reloaded_feature_extractor.__class__.__name__   ,   """NewFeatureExtractor"""				)







   def 						lowerCamelCase_	(     self						:						Union[str, Any]				):





    """simple docstring"""


    try:
     AutoConfig.register("""custom"""   ,   lowerCamelCase_				)
     AutoFeatureExtractor.register(lowerCamelCase_   ,   lowerCamelCase_				)
     # Trying to register something existing in the Transformers library will raise an error
     with self.assertRaises(lowerCamelCase_				):
      AutoFeatureExtractor.register(lowerCamelCase_   ,   lowerCamelCase_				)

     # Now that the config is registered, it can be used as any other config with the auto-API
     UpperCamelCase			  =      CustomFeatureExtractor.from_pretrained(lowerCamelCase_				)
     with tempfile.TemporaryDirectory() as tmp_dir:
      feature_extractor.save_pretrained(lowerCamelCase_				)
      UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(lowerCamelCase_				)
      self.assertIsInstance(lowerCamelCase_   ,   lowerCamelCase_				)

    finally:
     if "custom" in CONFIG_MAPPING._extra_content:
      del CONFIG_MAPPING._extra_content["custom"]
     if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
      del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]







   def 						lowerCamelCase_	(     self						:						Dict				):





    """simple docstring"""


    class SCREAMING_SNAKE_CASE_		(      __lowerCAmelCase		):
       __lowerCAmelCase           =				True

    try:
     AutoConfig.register("""custom"""   ,   lowerCamelCase_				)
     AutoFeatureExtractor.register(lowerCamelCase_   ,   lowerCamelCase_				)
     # If remote code is not set, the default is to use local
     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(
         """hf-internal-testing/test_dynamic_feature_extractor"""				)
     self.assertEqual(feature_extractor.__class__.__name__   ,   """NewFeatureExtractor"""				)
     self.assertTrue(feature_extractor.is_local				)

     # If remote code is disabled, we load the local one.
     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(
         """hf-internal-testing/test_dynamic_feature_extractor"""   ,   trust_remote_code=lowerCamelCase_				)
     self.assertEqual(feature_extractor.__class__.__name__   ,   """NewFeatureExtractor"""				)
     self.assertTrue(feature_extractor.is_local				)

     # If remote is enabled, we load from the Hub
     UpperCamelCase			  =      AutoFeatureExtractor.from_pretrained(
         """hf-internal-testing/test_dynamic_feature_extractor"""   ,   trust_remote_code=lowerCamelCase_				)
     self.assertEqual(feature_extractor.__class__.__name__   ,   """NewFeatureExtractor"""				)
     self.assertTrue(not hasattr(lowerCamelCase_   ,   """is_local"""				)				)

    finally:
     if "custom" in CONFIG_MAPPING._extra_content:
      del CONFIG_MAPPING._extra_content["custom"]
     if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
      del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
