


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        _a							(			datasets.BuilderConfig			):
							_lowercase	:			Optional[datasets.Features]        = None
def 			_a (      SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE						,				):


		"""simple docstring"""




		import pyspark

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

		return generate_fn


class        _a							(			_BaseExamplesIterable			):

							def __init__(							self:	List[str]    ,						UpperCamelCase_:	"pyspark.sql.DataFrame"    ,						UpperCamelCase_:	Tuple=None    ,						)			->   int:





									"""simple docstring"""







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

							def __iter__(							self:	Optional[Any]							)			->   List[str]:





									"""simple docstring"""







									yield from self.generate_examples_fn()

							def       lowerCamelCase_ (							self:	List[Any]    ,						UpperCamelCase_:	np.random.Generator							)			->   "SparkExamplesIterable":





									"""simple docstring"""







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

							def       lowerCamelCase_ (							self:	str    ,						UpperCamelCase_:	int    ,						UpperCamelCase_:	int							)			->   "SparkExamplesIterable":





									"""simple docstring"""







									lowercase__            =      self.split_shard_indices_by_worker(UpperCamelCase_    ,						UpperCamelCase_							)
									return SparkExamplesIterable(self.df    ,						partition_order=UpperCamelCase_							)


							@property
							def       lowerCamelCase_ (							self:	int							)			->   int:





									"""simple docstring"""







									return len(self.partition_order							)


class        _a							(			datasets.DatasetBuilder			):
							_lowercase	:			Tuple        = SparkConfig

							def __init__(							self:	Any    ,						UpperCamelCase_:	"pyspark.sql.DataFrame"    ,						UpperCamelCase_:	str = None    ,						UpperCamelCase_:	str = None    ,						**UpperCamelCase_:	Tuple    ,						)			->   int:





									"""simple docstring"""







									import pyspark

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

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

							def       lowerCamelCase_ (							self:	int							)			->   List[Any]:





									"""simple docstring"""







									def create_cache_and_write_probe(UpperCamelCase_:	Dict							):
											# 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=UpperCamelCase_							)
											lowercase__            =      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(UpperCamelCase_    ,						'''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:
											lowercase__            =      (
											    self._spark.sparkContext.parallelize(range(1							)    ,						1							).mapPartitions(UpperCamelCase_							).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       lowerCamelCase_ (							self:	str							)			->   Optional[int]:





									"""simple docstring"""







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

							def       lowerCamelCase_ (							self:	Tuple    ,						UpperCamelCase_:	datasets.download.download_manager.DownloadManager							)			->   Optional[int]:





									"""simple docstring"""







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

							def       lowerCamelCase_ (							self:	List[str]    ,						UpperCamelCase_:	List[str]							)			->   List[Any]:





									"""simple docstring"""







									import pyspark

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

									lowercase__            =      self.df.count()
									lowercase__            =      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.
									lowercase__            =      (
									    self.df.limit(UpperCamelCase_							)
									    .repartition(1							)
									    .mapInArrow(UpperCamelCase_    ,						'''batch_bytes: long'''							)
									    .agg(pyspark.sql.functions.sum('''batch_bytes'''							).alias('''sample_bytes'''							)							)
									    .collect()[0]
									    .sample_bytes
									    / sample_num_rows
									)
									lowercase__            =      approx_bytes_per_row * df_num_rows
									if approx_total_size > max_shard_size:
											# Make sure there is at least one row per partition.
											lowercase__            =      min(UpperCamelCase_    ,						int(approx_total_size / max_shard_size							)							)
											lowercase__            =      self.df.repartition(UpperCamelCase_							)

							def       lowerCamelCase_ (							self:	Dict    ,						UpperCamelCase_:	str    ,						UpperCamelCase_:	str    ,						UpperCamelCase_:	int    ,						)			->   Iterable[Tuple[int, bool, Union[int, tuple]]]:





									"""simple docstring"""







									import pyspark

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

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

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

									lowercase__            =      (
									    self.df.mapInArrow(UpperCamelCase_    ,						'''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       lowerCamelCase_ (							self:	Any    ,						UpperCamelCase_:	"datasets.SplitGenerator"    ,						UpperCamelCase_:	str = "arrow"    ,						UpperCamelCase_:	Optional[Union[str, int]] = None    ,						UpperCamelCase_:	Optional[int] = None    ,						**UpperCamelCase_:	Optional[int]    ,						)			->   str:





									"""simple docstring"""







									self._validate_cache_dir()

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

									lowercase__            =      '''-TTTTT-SSSSS-of-NNNNN'''
									lowercase__            =      f'{self.name}-{split_generator.name}{SUFFIX}.{file_format}'
									lowercase__            =      path_join(self._output_dir    ,						UpperCamelCase_							)

									lowercase__            =      0
									lowercase__            =      0
									lowercase__            =      0
									lowercase__            =      []
									lowercase__            =      []

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

									lowercase__            =      total_num_examples
									lowercase__            =      total_num_bytes

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

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

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


							def       lowerCamelCase_ (							self:	List[str]    ,						UpperCamelCase_:	"datasets.SplitGenerator"    ,						)			->   SparkExamplesIterable:





									"""simple docstring"""







									return SparkExamplesIterable(self.df							)






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
			import torch

if is_vision_available():
			from PIL import Image

			from transformers import LevitImageProcessor


class        _a							(			unittest.TestCase			):

							def __init__(							self:	Dict    ,						UpperCamelCase_:	Any    ,						UpperCamelCase_:	Dict=7    ,						UpperCamelCase_:	Optional[int]=3    ,						UpperCamelCase_:	List[Any]=18    ,						UpperCamelCase_:	Dict=30    ,						UpperCamelCase_:	Optional[int]=400    ,						UpperCamelCase_:	Optional[int]=True    ,						UpperCamelCase_:	Union[str, Any]=None    ,						UpperCamelCase_:	List[str]=True    ,						UpperCamelCase_:	Dict=None    ,						UpperCamelCase_:	Optional[int]=True    ,						UpperCamelCase_:	Tuple=[0.5, 0.5, 0.5]    ,						UpperCamelCase_:	List[str]=[0.5, 0.5, 0.5]    ,						)			->   int:





									"""simple docstring"""







									lowercase__            =      size if size is not None else {'''shortest_edge''': 18}
									lowercase__            =      crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
									lowercase__            =      parent
									lowercase__            =      batch_size
									lowercase__            =      num_channels
									lowercase__            =      image_size
									lowercase__            =      min_resolution
									lowercase__            =      max_resolution
									lowercase__            =      do_resize
									lowercase__            =      size
									lowercase__            =      do_center_crop
									lowercase__            =      crop_size
									lowercase__            =      do_normalize
									lowercase__            =      image_mean
									lowercase__            =      image_std


							def       lowerCamelCase_ (							self:	List[str]							)			->   Optional[Any]:





									"""simple docstring"""







									return {
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_normalize": self.do_normalize,
									    "do_resize": self.do_resize,
									    "do_center_crop": self.do_center_crop,
									    "size": self.size,
									    "crop_size": self.crop_size,
									}


@require_torch
@require_vision
class        _a							(			UpperCamelCase__     ,	unittest.TestCase			):
							_lowercase	:			List[str]        = LevitImageProcessor if is_vision_available() else None

							def       lowerCamelCase_ (							self:	Optional[Any]							)			->   List[str]:





									"""simple docstring"""







									lowercase__            =      LevitImageProcessingTester(self							)

							@property
							def       lowerCamelCase_ (							self:	List[Any]							)			->   Any:





									"""simple docstring"""







									return self.image_processor_tester.prepare_image_processor_dict()

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





									"""simple docstring"""







									lowercase__            =      self.image_processing_class(**self.image_processor_dict							)
									self.assertTrue(hasattr(UpperCamelCase_    ,						'''image_mean'''							)							)
									self.assertTrue(hasattr(UpperCamelCase_    ,						'''image_std'''							)							)
									self.assertTrue(hasattr(UpperCamelCase_    ,						'''do_normalize'''							)							)
									self.assertTrue(hasattr(UpperCamelCase_    ,						'''do_resize'''							)							)
									self.assertTrue(hasattr(UpperCamelCase_    ,						'''do_center_crop'''							)							)
									self.assertTrue(hasattr(UpperCamelCase_    ,						'''size'''							)							)

							def       lowerCamelCase_ (							self:	str							)			->   Tuple:





									"""simple docstring"""







									lowercase__            =      self.image_processing_class.from_dict(self.image_processor_dict							)
									self.assertEqual(image_processor.size    ,						{'''shortest_edge''': 18}							)
									self.assertEqual(image_processor.crop_size    ,						{'''height''': 18, '''width''': 18}							)

									lowercase__            =      self.image_processing_class.from_dict(self.image_processor_dict    ,						size=42    ,						crop_size=84							)
									self.assertEqual(image_processor.size    ,						{'''shortest_edge''': 42}							)
									self.assertEqual(image_processor.crop_size    ,						{'''height''': 84, '''width''': 84}							)

							def       lowerCamelCase_ (							self:	List[str]							)			->   Dict:





									"""simple docstring"""







									pass

							def       lowerCamelCase_ (							self:	List[str]							)			->   int:





									"""simple docstring"""







									lowercase__            =      self.image_processing_class(**self.image_processor_dict							)
									# create random PIL images
									lowercase__            =      prepare_image_inputs(self.image_processor_tester    ,						equal_resolution=UpperCamelCase_							)
									for image in image_inputs:
											self.assertIsInstance(UpperCamelCase_    ,						Image.Image							)

									# Test not batched input
									lowercase__            =      image_processing(image_inputs[0]    ,						return_tensors='''pt'''							).pixel_values
									self.assertEqual(
									    encoded_images.shape    ,						(
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,						)

									# Test batched
									lowercase__            =      image_processing(UpperCamelCase_    ,						return_tensors='''pt'''							).pixel_values
									self.assertEqual(
									    encoded_images.shape    ,						(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,						)

							def       lowerCamelCase_ (							self:	Union[str, Any]							)			->   Optional[int]:





									"""simple docstring"""







									lowercase__            =      self.image_processing_class(**self.image_processor_dict							)
									# create random numpy tensors
									lowercase__            =      prepare_image_inputs(self.image_processor_tester    ,						equal_resolution=UpperCamelCase_    ,						numpify=UpperCamelCase_							)
									for image in image_inputs:
											self.assertIsInstance(UpperCamelCase_    ,						np.ndarray							)

									# Test not batched input
									lowercase__            =      image_processing(image_inputs[0]    ,						return_tensors='''pt'''							).pixel_values
									self.assertEqual(
									    encoded_images.shape    ,						(
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,						)

									# Test batched
									lowercase__            =      image_processing(UpperCamelCase_    ,						return_tensors='''pt'''							).pixel_values
									self.assertEqual(
									    encoded_images.shape    ,						(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,						)


							def       lowerCamelCase_ (							self:	Any							)			->   Optional[Any]:





									"""simple docstring"""







									lowercase__            =      self.image_processing_class(**self.image_processor_dict							)
									# create random PyTorch tensors
									lowercase__            =      prepare_image_inputs(self.image_processor_tester    ,						equal_resolution=UpperCamelCase_    ,						torchify=UpperCamelCase_							)
									for image in image_inputs:
											self.assertIsInstance(UpperCamelCase_    ,						torch.Tensor							)

									# Test not batched input
									lowercase__            =      image_processing(image_inputs[0]    ,						return_tensors='''pt'''							).pixel_values
									self.assertEqual(
									    encoded_images.shape    ,						(
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,						)

									# Test batched
									lowercase__            =      image_processing(UpperCamelCase_    ,						return_tensors='''pt'''							).pixel_values
									self.assertEqual(
									    encoded_images.shape    ,						(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,						)


