


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							)




from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import fa_score, matthews_corrcoef

import datasets


lowercase  :					str						    =							"""\
@inproceedings{wang2019glue,
  title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},
  author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},
  note={In the Proceedings of ICLR.},
  year={2019}
}
"""

lowercase  :					Dict						    =							"""\
GLUE, the General Language Understanding Evaluation benchmark
(https://gluebenchmark.com/) is a collection of resources for training,
evaluating, and analyzing natural language understanding systems.
"""

lowercase  :					int						    =							"""
Compute GLUE evaluation metric associated to each GLUE dataset.
Args:
    predictions: list of predictions to score.
        Each translation should be tokenized into a list of tokens.
    references: list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
Returns: depending on the GLUE subset, one or several of:
    \"accuracy\": Accuracy
    \"f1\": F1 score
    \"pearson\": Pearson Correlation
    \"spearmanr\": Spearman Correlation
    \"matthews_correlation\": Matthew Correlation
Examples:

    >>> glue_metric = datasets.load_metric('glue', 'sst2')  # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0}

    >>> glue_metric = datasets.load_metric('glue', 'mrpc')  # 'mrpc' or 'qqp'
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0, 'f1': 1.0}

    >>> glue_metric = datasets.load_metric('glue', 'stsb')
    >>> references = [0., 1., 2., 3., 4., 5.]
    >>> predictions = [0., 1., 2., 3., 4., 5.]
    >>> results = glue_metric.compute(predictions=predictions, references=references)
    >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})
    {'pearson': 1.0, 'spearmanr': 1.0}

    >>> glue_metric = datasets.load_metric('glue', 'cola')
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'matthews_correlation': 1.0}
"""







def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    Optional[int]:
       return float((preds == labels).mean()				)







def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    Optional[Any]:
       lowercase							:     Any       	=      simple_accuracy(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)
       lowercase							:     Union[str, Any]       	=      float(fa_score(y_true=SCREAMING_SNAKE_CASE__					,	y_pred=SCREAMING_SNAKE_CASE__				)				)
       return {
           "accuracy": acc,
           "f1": fa,
       }







def 						_snake_case(  SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				) ->    List[Any]:
       lowercase							:     Union[str, Any]       	=      float(pearsonr(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)[0]				)
       lowercase							:     Dict       	=      float(spearmanr(SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__				)[0]				)
       return {
           "pearson": pearson_corr,
           "spearmanr": spearman_corr,
       }




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					,	_KWARGS_DESCRIPTION     )
class __snake_case		(      datasets.Metric     ):
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           if self.config_name not in [
               "sst2",
               "mnli",
               "mnli_mismatched",
               "mnli_matched",
               "cola",
               "stsb",
               "mrpc",
               "qqp",
               "qnli",
               "rte",
               "wnli",
               "hans",
           ]:
                  raise KeyError(
                      """You should supply a configuration name selected in """
                      """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """
                      """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]"""      )
           return datasets.MetricInfo(
               description=_DESCRIPTION		,citation=_CITATION		,inputs_description=_KWARGS_DESCRIPTION		,features=datasets.Features(
                   {
                       """predictions""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32"""      ),
                       """references""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32"""      ),
                   }      )		,codebase_urls=[]		,reference_urls=[]		,format="""numpy"""		,)
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case      ):



           '''simple docstring'''







           if self.config_name == "cola":
                  return {"matthews_correlation": matthews_corrcoef(snake_case		,snake_case      )}
           elif self.config_name == "stsb":
                  return pearson_and_spearman(snake_case		,snake_case      )
           elif self.config_name in ["mrpc", "qqp"]:
                  return acc_and_fa(snake_case		,snake_case      )
           elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]:
                  return {"accuracy": simple_accuracy(snake_case		,snake_case      )}
           else:
                  raise KeyError(
                      """You should supply a configuration name selected in """
                      """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """
                      """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]"""      )
