





'''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					    =	datasets.utils.logging.get_logger(__name__)

__UpperCamelCase					    =	["names", "prefix"]
__UpperCamelCase					    =	["warn_bad_lines", "error_bad_lines", "mangle_dupe_cols"]
__UpperCamelCase					    =	["encoding_errors", "on_bad_lines"]
__UpperCamelCase					    =	["date_format"]




@dataclass
class  _A (					datasets.BuilderConfig		):
		lowercase__:   str				     =   ","
		lowercase__:   Optional[str]				     =   None
		lowercase__:   Optional[Union[int, List[int], str]]				     =   "infer"
		lowercase__:   Optional[List[str]]				     =   None
		lowercase__:   Optional[List[str]]				     =   None
		lowercase__:   Optional[Union[int, str, List[int], List[str]]]				     =   None
		lowercase__:   Optional[Union[List[int], List[str]]]				     =   None
		lowercase__:   Optional[str]				     =   None
		lowercase__:   bool				     =   True
		lowercase__:   Optional[Literal["c", "python", "pyarrow"]]				     =   None
		lowercase__:   Dict[Union[int, str], Callable[[Any], Any]]				     =   None
		lowercase__:   Optional[list]				     =   None
		lowercase__:   Optional[list]				     =   None
		lowercase__:   bool				     =   False
		lowercase__:   Optional[Union[int, List[int]]]				     =   None
		lowercase__:   Optional[int]				     =   None
		lowercase__:   Optional[Union[str, List[str]]]				     =   None
		lowercase__:   bool				     =   True
		lowercase__:   bool				     =   True
		lowercase__:   bool				     =   False
		lowercase__:   bool				     =   True
		lowercase__:   Optional[str]				     =   None
		lowercase__:   str				     =   "."
		lowercase__:   Optional[str]				     =   None
		lowercase__:   str				     =   '"'
		lowercase__:   int				     =   0
		lowercase__:   Optional[str]				     =   None
		lowercase__:   Optional[str]				     =   None
		lowercase__:   Optional[str]				     =   None
		lowercase__:   Optional[str]				     =   None
		lowercase__:   bool				     =   True
		lowercase__:   bool				     =   True
		lowercase__:   int				     =   0
		lowercase__:   bool				     =   True
		lowercase__:   bool				     =   False
		lowercase__:   Optional[str]				     =   None
		lowercase__:   int				     =   10000
		lowercase__:   Optional[datasets.Features]				     =   None
		lowercase__:   Optional[str]				     =   "strict"
		lowercase__:   Literal["error", "warn", "skip"]				     =   "error"
		lowercase__:   Optional[str]				     =   None

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


					"""simple docstring"""

					if self.delimiter is not None:
								__snake_case					:      Any							      =     self.delimiter
					if self.column_names is not None:
								__snake_case					:      Optional[Any]							      =     self.column_names

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


					"""simple docstring"""

					__snake_case					:      str							      =     {
					    """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()  ,      __magic_name__			):
											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		):
		lowercase__:   List[Any]				     =   CsvConfig

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


					"""simple docstring"""

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

		def 	lowercase__     (   self					:   List[str]  ,      __magic_name__					:   Optional[int]			)					->    Dict:


					"""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}'''			)
					__snake_case					:      Tuple							      =     dl_manager.download_and_extract(self.config.data_files			)
					if isinstance(__magic_name__  ,      (str, list, tuple)			):
								__snake_case					:      int							      =     data_files
								if isinstance(__magic_name__  ,      __magic_name__			):
											__snake_case					:      Optional[int]							      =     [files]
								__snake_case					:      Tuple							      =     [dl_manager.iter_files(__magic_name__			) for file in files]
								return [datasets.SplitGenerator(name=datasets.Split.TRAIN  ,      gen_kwargs={"""files""": files}			)]
					__snake_case					:      Optional[Any]							      =     []
					for split_name, files in data_files.items():
								if isinstance(__magic_name__  ,      __magic_name__			):
											__snake_case					:      Optional[Any]							      =     [files]
								__snake_case					:      Optional[int]							      =     [dl_manager.iter_files(__magic_name__			) for file in files]
								splits.append(datasets.SplitGenerator(name=__magic_name__  ,      gen_kwargs={"""files""": files}			)			)
					return splits

		def 	lowercase__     (   self					:   Optional[Any]  ,      __magic_name__					:   pa.Table			)					->    pa.Table:


					"""simple docstring"""

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

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


					"""simple docstring"""

					__snake_case					:      List[str]							      =     self.config.features.arrow_schema if self.config.features else None
					# dtype allows reading an int column as str
					__snake_case					:      Union[str, Any]							      =     (
					    {
					        name: dtype.to_pandas_dtype() if not require_storage_cast(__magic_name__			) 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(__magic_name__			)			):
								__snake_case					:      Optional[int]							      =     pd.read_csv(__magic_name__  ,      iterator=__magic_name__  ,      dtype=__magic_name__  ,      **self.config.pd_read_csv_kwargs			)
								try:
											for batch_idx, df in enumerate(__magic_name__			):
														__snake_case					:      List[str]							      =     pa.Table.from_pandas(__magic_name__			)
														# 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(__magic_name__			)
								except ValueError as e:
											logger.error(f'''Failed to read file \'{file}\' with error {type(__magic_name__			)}: {e}'''			)
											raise









'''simple docstring'''






from unittest import TestCase

from datasets import Sequence, Value
from datasets.arrow_dataset import Dataset




class  _A (					__lowercase		):

		def 	lowercase__     (   self					:   Any			)					->    str:


					"""simple docstring"""

					return [
					    {"col_1": 3, "col_2": "a"},
					    {"col_1": 2, "col_2": "b"},
					    {"col_1": 1, "col_2": "c"},
					    {"col_1": 0, "col_2": "d"},
					]

		def 	lowercase__     (   self					:   str			)					->    int:


					"""simple docstring"""

					__snake_case					:      Union[str, Any]							      =     {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]}
					return Dataset.from_dict(__magic_name__			)

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


					"""simple docstring"""

					__snake_case					:      Any							      =     self._create_example_records()
					__snake_case					:      str							      =     Dataset.from_list(__magic_name__			)
					self.assertListEqual(dset.column_names  ,      ["""col_1""", """col_2"""]			)
					for i, r in enumerate(__magic_name__			):
								self.assertDictEqual(__magic_name__  ,      example_records[i]			)

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


					"""simple docstring"""

					__snake_case					:      List[Any]							      =     self._create_example_records()
					__snake_case					:      Dict							      =     Dataset.from_list(__magic_name__			)
					__snake_case					:      List[Any]							      =     Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]}			)
					self.assertEqual(dset.info  ,      dset_from_dict.info			)

		def 	lowercase__     (   self					:   str			)					->    List[Any]:  # checks what happens with missing columns


					"""simple docstring"""

					__snake_case					:      Union[str, Any]							      =     [{"""col_1""": 1}, {"""col_2""": """x"""}]
					__snake_case					:      Optional[int]							      =     Dataset.from_list(__magic_name__			)
					self.assertDictEqual(dset[0]  ,      {"""col_1""": 1}			)
					self.assertDictEqual(dset[1]  ,      {"""col_1""": None}			)  # NB: first record is used for columns

		def 	lowercase__     (   self					:   List[str]			)					->    Optional[Any]:  # checks if the type can be inferred from the second record


					"""simple docstring"""

					__snake_case					:      List[Any]							      =     [{"""col_1""": []}, {"""col_1""": [1, 2]}]
					__snake_case					:      int							      =     Dataset.from_list(__magic_name__			)
					self.assertEqual(dset.info.features["""col_1"""]  ,      Sequence(Value("""int64"""			)			)			)

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


					"""simple docstring"""

					__snake_case					:      Tuple							      =     Dataset.from_list([]			)
					self.assertEqual(len(__magic_name__			)  ,      0			)
					self.assertListEqual(dset.column_names  ,      []			)


