


"""simple docstring"""






import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


UpperCamelCase__				:Union[str, Any]			   =	datasets.utils.logging.get_logger(__name__)

UpperCamelCase__				:List[str]			   =	["""names""", """prefix"""]
UpperCamelCase__				:Dict			   =	["""warn_bad_lines""", """error_bad_lines""", """mangle_dupe_cols"""]
UpperCamelCase__				:List[Any]			   =	["""encoding_errors""", """on_bad_lines"""]
UpperCamelCase__				:Optional[Any]			   =	["""date_format"""]






@dataclass
class      A(  datasets.BuilderConfig		):

		"""simple docstring"""





		A    =							","
		A    =							None
		A    =							"infer"
		A    =							None
		A    =							None
		A    =							None
		A    =							None
		A    =							None
		A    =							True
		A    =							None
		A    =							None
		A    =							None
		A    =							None
		A    =							False
		A    =							None
		A    =							None
		A    =							None
		A    =							True
		A    =							True
		A    =							False
		A    =							True
		A    =							None
		A    =							"."
		A    =							None
		A    =							'"'
		A    =							0
		A    =							None
		A    =							None
		A    =							None
		A    =							None
		A    =							True
		A    =							True
		A    =							0
		A    =							True
		A    =							False
		A    =							None
		A    =							1_00_00
		A    =							None
		A    =							"strict"
		A    =							"error"
		A    =							None
		def   _UpperCamelCase( self   )      ->	Optional[int]:

					"""simple docstring"""



					if self.delimiter is not None:
								_UpperCamelCase					:List[Any]					     =	self.delimiter
					if self.column_names is not None:
								_UpperCamelCase					:List[str]					     =	self.column_names





		@property
		def   _UpperCamelCase( self   )      ->	List[str]:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	{
					    '''sep''': self.sep,
					    '''header''': self.header,
					    '''names''': self.names,
					    '''index_col''': self.index_col,
					    '''usecols''': self.usecols,
					    '''prefix''': self.prefix,
					    '''mangle_dupe_cols''': self.mangle_dupe_cols,
					    '''engine''': self.engine,
					    '''converters''': self.converters,
					    '''true_values''': self.true_values,
					    '''false_values''': self.false_values,
					    '''skipinitialspace''': self.skipinitialspace,
					    '''skiprows''': self.skiprows,
					    '''nrows''': self.nrows,
					    '''na_values''': self.na_values,
					    '''keep_default_na''': self.keep_default_na,
					    '''na_filter''': self.na_filter,
					    '''verbose''': self.verbose,
					    '''skip_blank_lines''': self.skip_blank_lines,
					    '''thousands''': self.thousands,
					    '''decimal''': self.decimal,
					    '''lineterminator''': self.lineterminator,
					    '''quotechar''': self.quotechar,
					    '''quoting''': self.quoting,
					    '''escapechar''': self.escapechar,
					    '''comment''': self.comment,
					    '''encoding''': self.encoding,
					    '''dialect''': self.dialect,
					    '''error_bad_lines''': self.error_bad_lines,
					    '''warn_bad_lines''': self.warn_bad_lines,
					    '''skipfooter''': self.skipfooter,
					    '''doublequote''': self.doublequote,
					    '''memory_map''': self.memory_map,
					    '''float_precision''': self.float_precision,
					    '''chunksize''': self.chunksize,
					    '''encoding_errors''': self.encoding_errors,
					    '''on_bad_lines''': self.on_bad_lines,
					    '''date_format''': self.date_format,
					}

					# some kwargs must not be passed if they don't have a default value
					# some others are deprecated and we can also not pass them if they are the default value
					for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
								if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()					,				SCREAMING_SNAKE_CASE__   ):
											del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
					if not (datasets.config.PANDAS_VERSION.major >= 2):
								for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
											del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
					if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
								for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
											del pd_read_csv_kwargs[pd_read_csv_parameter]

					return pd_read_csv_kwargs






class      A(  datasets.ArrowBasedBuilder		):

		"""simple docstring"""





		A    =							CsvConfig
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



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

					"""simple docstring"""



					if not self.config.data_files:
								raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}"   )
					_UpperCamelCase					:str					     =	dl_manager.download_and_extract(self.config.data_files   )
					if isinstance(SCREAMING_SNAKE_CASE__					,				(str, list, tuple)   ):
								_UpperCamelCase					:List[Any]					     =	data_files
								if isinstance(SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   ):
											_UpperCamelCase					:Dict					     =	[files]
								_UpperCamelCase					:Optional[int]					     =	[dl_manager.iter_files(SCREAMING_SNAKE_CASE__   ) for file in files]
								return [datasets.SplitGenerator(name=datasets.Split.TRAIN					,				gen_kwargs={'''files''': files}   )]
					_UpperCamelCase					:str					     =	[]
					for split_name, files in data_files.items():
								if isinstance(SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   ):
											_UpperCamelCase					:Dict					     =	[files]
								_UpperCamelCase					:Union[str, Any]					     =	[dl_manager.iter_files(SCREAMING_SNAKE_CASE__   ) for file in files]
								splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE__					,				gen_kwargs={'''files''': files}   )   )
					return splits
		def   _UpperCamelCase( self					,				SCREAMING_SNAKE_CASE__   )      ->	pa.Table:

					"""simple docstring"""



					if self.config.features is not None:
								_UpperCamelCase					:str					     =	self.config.features.arrow_schema
								if all(not require_storage_cast(SCREAMING_SNAKE_CASE__   ) for feature in self.config.features.values()   ):
											# cheaper cast
											_UpperCamelCase					:Dict					     =	pa.Table.from_arrays([pa_table[field.name] for field in schema]					,				schema=SCREAMING_SNAKE_CASE__   )
								else:
											# more expensive cast; allows str <-> int/float or str to Audio for example
											_UpperCamelCase					:List[Any]					     =	table_cast(SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )
					return pa_table





		def   _UpperCamelCase( self					,				SCREAMING_SNAKE_CASE__   )      ->	List[str]:

					"""simple docstring"""



					_UpperCamelCase					:Any					     =	self.config.features.arrow_schema if self.config.features else None
					# dtype allows reading an int column as str
					_UpperCamelCase					:Optional[int]					     =	(
					    {
					        name: dtype.to_pandas_dtype() if not require_storage_cast(SCREAMING_SNAKE_CASE__   ) else object
					        for name, dtype, feature in zip(schema.names					,				schema.types					,				self.config.features.values()   )
					    }
					    if schema is not None
					    else None
					)
					for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE__   )   ):
								_UpperCamelCase					:Union[str, Any]					     =	pd.read_csv(SCREAMING_SNAKE_CASE__					,				iterator=SCREAMING_SNAKE_CASE__					,				dtype=SCREAMING_SNAKE_CASE__					,				**self.config.pd_read_csv_kwargs   )
								try:
											for batch_idx, df in enumerate(SCREAMING_SNAKE_CASE__   ):
														_UpperCamelCase					:Tuple					     =	pa.Table.from_pandas(SCREAMING_SNAKE_CASE__   )
														# Uncomment for debugging (will print the Arrow table size and elements)
														# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
														# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
														yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE__   )
								except ValueError as e:
											logger.error(f"Failed to read file '{file}' with error {type(SCREAMING_SNAKE_CASE__   )}: {e}"   )
											raise





"""simple docstring"""






import unittest

import numpy as np

from transformers.testing_utils import require_flax, require_tf, require_torch
from transformers.utils import (
    expand_dims,
    flatten_dict,
    is_flax_available,
    is_tf_available,
    is_torch_available,
    reshape,
    squeeze,
    transpose,
)


if is_flax_available():
					import jax.numpy as jnp

if is_tf_available():
					import tensorflow as tf

if is_torch_available():
					import torch






class      A(  unittest.TestCase		):

		"""simple docstring"""





		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	{
					    '''task_specific_params''': {
					        '''summarization''': {'''length_penalty''': 1.0, '''max_length''': 1_28, '''min_length''': 12, '''num_beams''': 4},
					        '''summarization_cnn''': {'''length_penalty''': 2.0, '''max_length''': 1_42, '''min_length''': 56, '''num_beams''': 4},
					        '''summarization_xsum''': {'''length_penalty''': 1.0, '''max_length''': 62, '''min_length''': 11, '''num_beams''': 6},
					    }
					}
					_UpperCamelCase					:Union[str, Any]					     =	{
					    '''task_specific_params.summarization.length_penalty''': 1.0,
					    '''task_specific_params.summarization.max_length''': 1_28,
					    '''task_specific_params.summarization.min_length''': 12,
					    '''task_specific_params.summarization.num_beams''': 4,
					    '''task_specific_params.summarization_cnn.length_penalty''': 2.0,
					    '''task_specific_params.summarization_cnn.max_length''': 1_42,
					    '''task_specific_params.summarization_cnn.min_length''': 56,
					    '''task_specific_params.summarization_cnn.num_beams''': 4,
					    '''task_specific_params.summarization_xsum.length_penalty''': 1.0,
					    '''task_specific_params.summarization_xsum.max_length''': 62,
					    '''task_specific_params.summarization_xsum.min_length''': 11,
					    '''task_specific_params.summarization_xsum.num_beams''': 6,
					}

					self.assertEqual(flatten_dict(SCREAMING_SNAKE_CASE__   )					,				SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	Any:

					"""simple docstring"""



					_UpperCamelCase					:Optional[int]					     =	np.random.randn(3					,				4   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				x.transpose()   )   )

					_UpperCamelCase					:Tuple					     =	np.random.randn(3					,				4					,				5   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				x.transpose((1, 2, 0)   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Any					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				transpose(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:int					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Any					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:List[str]					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				transpose(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:int					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Dict					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   ).numpy()   )   )
		@require_flax
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Optional[Any]					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				np.asarray(transpose(SCREAMING_SNAKE_CASE__   )   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Dict					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				np.asarray(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )   )   )   )
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	np.random.randn(3					,				4   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				np.reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4					,				5   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				np.reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Optional[Any]					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   ).numpy()   )   )

					_UpperCamelCase					:str					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:str					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:Optional[int]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Dict					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   ).numpy()   )   )

					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Optional[int]					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   ).numpy()   )   )
		@require_flax
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:str					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				np.asarray(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Union[str, Any]					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				np.asarray(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )   )   )   )
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	np.random.randn(1					,				3					,				4   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				np.squeeze(SCREAMING_SNAKE_CASE__   )   )   )

					_UpperCamelCase					:List[Any]					     =	np.random.randn(1					,				4					,				1					,				5   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				np.squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	np.random.randn(1					,				3					,				4   )
					_UpperCamelCase					:Any					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				squeeze(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:List[str]					     =	np.random.randn(1					,				4					,				1					,				5   )
					_UpperCamelCase					:List[Any]					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	np.random.randn(1					,				3					,				4   )
					_UpperCamelCase					:str					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				squeeze(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:str					     =	np.random.randn(1					,				4					,				1					,				5   )
					_UpperCamelCase					:str					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   ).numpy()   )   )
		@require_flax
		def   _UpperCamelCase( self   )      ->	Optional[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(1					,				3					,				4   )
					_UpperCamelCase					:Optional[Any]					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				np.asarray(squeeze(SCREAMING_SNAKE_CASE__   )   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(1					,				4					,				1					,				5   )
					_UpperCamelCase					:int					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				np.asarray(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )   )   )   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				np.expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Union[str, Any]					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	Optional[int]:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:int					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   ).numpy()   )   )





		@require_flax
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Tuple					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:str					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				np.asarray(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )   )   )   )

