
'''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


SCREAMING_SNAKE_CASE     =       datasets.utils.logging.get_logger(__name__)

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






@dataclass
class 							UpperCAmelCase_							(    datasets.BuilderConfig				):

 '''simple docstring'''
 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				=							10_000
 lowercase_					:    Optional[datasets.Features]				=							None
 lowercase_					:    Optional[str]				=							"strict"
 lowercase_					:    Literal["error", "warn", "skip"]				=							"error"
 lowercase_					:    Optional[str]				=							None







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   if self.delimiter is not None:
     UpperCAmelCase__      :					Optional[Any]				       =							self.delimiter
   if self.column_names is not None:
     UpperCAmelCase__      :					Union[str, Any]				       =							self.column_names







 @property
 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[Any]				       =							{
       "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()			,				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 							UpperCAmelCase_							(    datasets.ArrowBasedBuilder				):

 '''simple docstring'''
 lowercase_					:    List[Any]				=							CsvConfig







 def 							UpperCamelCase  (					self		:  Optional[Any] ):



   '''simple docstring'''




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







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







 def 							UpperCamelCase  (					self		:  int			,				snake_case__		:  pa.Table ):



   '''simple docstring'''




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







 def 							UpperCamelCase  (					self		:  Tuple			,				snake_case__		:  str ):



   '''simple docstring'''




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





'''simple docstring'''





import unittest

from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate







def snake_case_     (					lowercase__		):
  return x + 2






class 							UpperCAmelCase_							(    unittest.TestCase				):

 '''simple docstring'''







 def 							UpperCamelCase  (					self		:  Optional[int] ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[str]				       =							"x = 3"
   UpperCAmelCase__      :					List[str]				       =							{}
   UpperCAmelCase__      :					Tuple				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result == 3
   self.assertDictEqual(snake_case__			,				{"x": 3} )

   UpperCAmelCase__      :					Any				       =							"x = y"
   UpperCAmelCase__      :					List[str]				       =							{"y": 5}
   UpperCAmelCase__      :					Dict				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 5, "y": 5} )







 def 							UpperCamelCase  (					self		:  Union[str, Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							"y = add_two(x)"
   UpperCAmelCase__      :					Tuple				       =							{"x": 3}
   UpperCAmelCase__      :					Union[str, Any]				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 5} )

   # Won't work without the tool
   with CaptureStdout() as out:
     UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result is None
   assert "tried to execute add_two" in out.out







 def 							UpperCamelCase  (					self		:  List[str] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Tuple				       =							"x = 3"
   UpperCAmelCase__      :					List[Any]				       =							{}
   UpperCAmelCase__      :					Tuple				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result == 3
   self.assertDictEqual(snake_case__			,				{"x": 3} )







 def 							UpperCamelCase  (					self		:  Dict ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							"test_dict = {'x': x, 'y': add_two(x)}"
   UpperCAmelCase__      :					List[Any]				       =							{"x": 3}
   UpperCAmelCase__      :					int				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 5} )
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_dict": {"x": 3, "y": 5}} )







 def 							UpperCamelCase  (					self		:  List[str] ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							"x = 3\ny = 5"
   UpperCAmelCase__      :					Dict				       =							{}
   UpperCAmelCase__      :					Union[str, Any]				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 5} )







 def 							UpperCamelCase  (					self		:  Union[str, Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Dict				       =							"text = f'This is x: {x}.'"
   UpperCAmelCase__      :					Dict				       =							{"x": 3}
   UpperCAmelCase__      :					Dict				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == "This is x: 3."
   self.assertDictEqual(snake_case__			,				{"x": 3, "text": "This is x: 3."} )







 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[str]				       =							"if x <= 3:\n    y = 2\nelse:\n    y = 5"
   UpperCAmelCase__      :					Dict				       =							{"x": 3}
   UpperCAmelCase__      :					Dict				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 2
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 2} )

   UpperCAmelCase__      :					Optional[Any]				       =							{"x": 8}
   UpperCAmelCase__      :					str				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 8, "y": 5} )







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							"test_list = [x, add_two(x)]"
   UpperCAmelCase__      :					Any				       =							{"x": 3}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   self.assertListEqual(snake_case__			,				[3, 5] )
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_list": [3, 5]} )







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					str				       =							"y = x"
   UpperCAmelCase__      :					str				       =							{"x": 3}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result == 3
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 3} )







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							"test_list = [x, add_two(x)]\ntest_list[1]"
   UpperCAmelCase__      :					List[Any]				       =							{"x": 3}
   UpperCAmelCase__      :					List[Any]				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_list": [3, 5]} )

   UpperCAmelCase__      :					Union[str, Any]				       =							"test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']"
   UpperCAmelCase__      :					str				       =							{"x": 3}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_dict": {"x": 3, "y": 5}} )







 def 							UpperCamelCase  (					self		:  Union[str, Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[Any]				       =							"x = 0\nfor i in range(3):\n    x = i"
   UpperCAmelCase__      :					List[Any]				       =							{}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{"range": range}			,				state=snake_case__ )
   assert result == 2
   self.assertDictEqual(snake_case__			,				{"x": 2, "i": 2} )



