



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


__snake_case     :List[Any]			       =datasets.utils.logging.get_logger(__name__)

if TYPE_CHECKING:
				import pyspark



@dataclass
class        lowerCAmelCase__					(  datasets.BuilderConfig       ):
				A_   :     Optional[datasets.Features]								=     None






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

							'''simple docstring'''






							import pyspark

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

							return generate_fn



class        lowerCAmelCase__					(  _BaseExamplesIterable       ):


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


				def __iter__(							self      :  List[str]       )		->     Union[str, Any]:
											yield from self.generate_examples_fn()


				def __UpperCamelCase						(							self      :  Tuple						, __UpperCamelCase      :  np.random.Generator       )		->     "SparkExamplesIterable":
											A      						=    list(range(self.df.rdd.getNumPartitions()       )       )
											generator.shuffle(__UpperCamelCase       )
											return SparkExamplesIterable(self.df						, partition_order=__UpperCamelCase       )


				def __UpperCamelCase						(							self      :  Tuple						, __UpperCamelCase      :  int						, __UpperCamelCase      :  int       )		->     "SparkExamplesIterable":
											A      						=    self.split_shard_indices_by_worker(__UpperCamelCase						, __UpperCamelCase       )
											return SparkExamplesIterable(self.df						, partition_order=__UpperCamelCase       )


				@property
				def __UpperCamelCase						(							self      :  List[Any]       )		->     int:
											return len(self.partition_order       )





class        lowerCAmelCase__					(  datasets.DatasetBuilder       ):
				A_   :     Union[str, Any]								=     SparkConfig


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

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

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


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     Dict:
											# Returns the path of the created file.
											def create_cache_and_write_probe(__UpperCamelCase      :  Any       ):
																		# 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       )
																		A      						=    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:
																		A      						=    (
																		    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 __UpperCamelCase						(							self      :  str       )		->     Optional[Any]:
											return datasets.DatasetInfo(features=self.config.features       )


				def __UpperCamelCase						(							self      :  Dict						, __UpperCamelCase      :  datasets.download.download_manager.DownloadManager       )		->     Optional[Any]:
											return [datasets.SplitGenerator(name=datasets.Split.TRAIN       )]


				def __UpperCamelCase						(							self      :  Optional[Any]						, __UpperCamelCase      :  List[str]       )		->     str:
											import pyspark

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

											A      						=    self.df.count()
											A      						=    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.
											A      						=    (
											    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
											)
											A      						=    approx_bytes_per_row * df_num_rows
											if approx_total_size > max_shard_size:
																		# Make sure there is at least one row per partition.
																		A      						=    min(__UpperCamelCase						, int(approx_total_size / max_shard_size       )       )
																		A      						=    self.df.repartition(__UpperCamelCase       )


				def __UpperCamelCase						(							self      :  List[Any]						, __UpperCamelCase      :  str						, __UpperCamelCase      :  str						, __UpperCamelCase      :  int						, )		->     Iterable[Tuple[int, bool, Union[int, tuple]]]:
											import pyspark

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

											def write_arrow(__UpperCamelCase      :  Dict       ):
																		# Within the same SparkContext, no two task attempts will share the same attempt ID.
																		A      						=    pyspark.TaskContext().taskAttemptId()
																		A      						=    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']						, )
																		A      						=    0
																		A      						=    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						, )
																		A      						=    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:
																																A						,   A      						=    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
																																A      						=    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						, )
																									A      						=    pa.Table.from_batches([batch]       )
																									writer.write_table(__UpperCamelCase       )

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

											A      						=    (
											    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 __UpperCamelCase						(							self      :  str						, __UpperCamelCase      :  "datasets.SplitGenerator"						, __UpperCamelCase      :  str = "arrow"						, __UpperCamelCase      :  Optional[Union[str, int]] = None						, __UpperCamelCase      :  Optional[int] = None						, **__UpperCamelCase      :  Optional[int]						, )		->     int:
											self._validate_cache_dir()

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

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

											A      						=    0
											A      						=    0
											A      						=    0
											A      						=    []
											A      						=    []

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

											A      						=    total_num_examples
											A      						=    total_num_bytes

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

																		A      						=    []
																		A      						=    0
																		for i in range(len(__UpperCamelCase       )       ):
																									A						,   A      						=    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
																		A      						=    0
																		A      						=    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 __UpperCamelCase						(							self      :  Union[str, Any]						, __UpperCamelCase      :  "datasets.SplitGenerator"						, )		->     SparkExamplesIterable:
											return SparkExamplesIterable(self.df       )
import contextlib
import os
import sqlitea

import pytest

from datasets import Dataset, Features, Value
from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy
def 		snake_case__	(		lowercase							,				lowercase					):
   assert isinstance(lowercase							,				lowercase					)
   assert dataset.num_rows == 4
   assert dataset.num_columns == 3
   assert dataset.column_names == ["col_1", "col_2", "col_3"]
   for feature, expected_dtype in expected_features.items():
      assert dataset.features[feature].dtype == expected_dtype
@require_sqlalchemy
@pytest.mark.parametrize("keep_in_memory"							,				[False, True]					)
def 		snake_case__	(		lowercase							,				lowercase							,				lowercase							,				lowercase					):
   lowerCAmelCase_:							Any       =	tmp_path / "cache"
   lowerCAmelCase_:							int       =	{"col_1": "string", "col_2": "int64", "col_3": "float64"}
   with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
      lowerCAmelCase_:							Optional[int]       =	SqlDatasetReader(
          "dataset"							,				"sqlite:///" + sqlite_path							,				cache_dir=lowercase							,				keep_in_memory=lowercase					).read()
   _check_sql_dataset(lowercase							,				lowercase					)
@require_sqlalchemy
@pytest.mark.parametrize(
    "features"							,				[
        None,
        {"col_1": "string", "col_2": "int64", "col_3": "float64"},
        {"col_1": "string", "col_2": "string", "col_3": "string"},
        {"col_1": "int32", "col_2": "int32", "col_3": "int32"},
        {"col_1": "float32", "col_2": "float32", "col_3": "float32"},
    ]							,				)
def 		snake_case__	(		lowercase							,				lowercase							,				lowercase							,				lowercase					):
   lowerCAmelCase_:							List[str]       =	tmp_path / "cache"
   lowerCAmelCase_:							int       =	{"col_1": "string", "col_2": "int64", "col_3": "float64"}
   lowerCAmelCase_:							List[str]       =	features.copy() if features else default_expected_features
   lowerCAmelCase_:							Any       =	(
       Features({feature: Value(lowercase					) for feature, dtype in features.items()}					) if features is not None else None
   )
   lowerCAmelCase_:							int       =	SqlDatasetReader("dataset"							,				"sqlite:///" + sqlite_path							,				features=lowercase							,				cache_dir=lowercase					).read()
   _check_sql_dataset(lowercase							,				lowercase					)
def 		snake_case__	(		lowercase					):
   with contextlib.closing(sqlitea.connect(lowercase					)					) as con:
      lowerCAmelCase_:							Any       =	con.cursor()
      cur.execute("SELECT * FROM dataset"					)
      for row in cur:
         yield row
@require_sqlalchemy
def 		snake_case__	(		lowercase							,				lowercase							,				lowercase					):
   lowerCAmelCase_:							Optional[int]       =	tmp_path / "cache"
   lowerCAmelCase_:							Optional[Any]       =	os.path.join(lowercase							,				"tmp.sql"					)
   lowerCAmelCase_:							str       =	SqlDatasetReader("dataset"							,				"sqlite:///" + sqlite_path							,				cache_dir=lowercase					).read()
   SqlDatasetWriter(lowercase							,				"dataset"							,				"sqlite:///" + output_sqlite_path							,				num_proc=1					).write()

   lowerCAmelCase_:							Union[str, Any]       =	iter_sql_file(lowercase					)
   lowerCAmelCase_:							str       =	iter_sql_file(lowercase					)

   for rowa, rowa in zip(lowercase							,				lowercase					):
      assert rowa == rowa
@require_sqlalchemy
def 		snake_case__	(		lowercase							,				lowercase							,				lowercase					):
   lowerCAmelCase_:							str       =	tmp_path / "cache"
   lowerCAmelCase_:							Optional[int]       =	os.path.join(lowercase							,				"tmp.sql"					)
   lowerCAmelCase_:							Optional[Any]       =	SqlDatasetReader("dataset"							,				"sqlite:///" + sqlite_path							,				cache_dir=lowercase					).read()
   SqlDatasetWriter(lowercase							,				"dataset"							,				"sqlite:///" + output_sqlite_path							,				num_proc=2					).write()

   lowerCAmelCase_:							Optional[Any]       =	iter_sql_file(lowercase					)
   lowerCAmelCase_:							Optional[int]       =	iter_sql_file(lowercase					)

   for rowa, rowa in zip(lowercase							,				lowercase					):
      assert rowa == rowa







@require_sqlalchemy
def 		snake_case__	(		lowercase							,				lowercase							,				lowercase					):
   lowerCAmelCase_:							Union[str, Any]       =	tmp_path / "cache"
   lowerCAmelCase_:							int       =	os.path.join(lowercase							,				"tmp.sql"					)
   lowerCAmelCase_:							Any       =	SqlDatasetReader("dataset"							,				"sqlite:///" + sqlite_path							,				cache_dir=lowercase					).read()
   with pytest.raises(lowercase					):
      SqlDatasetWriter(lowercase							,				"dataset"							,				"sqlite:///" + output_sqlite_path							,				num_proc=0					).write()