

import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('''3.8'''):
       import importlib_metadata
else:
       import importlib.metadata as importlib_metadata

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Optional[int]	,     SCREAMING_SNAKE_CASE_		:    Optional[Any]=False			):



     '''simple docstring'''





     try:
          lowercase__    :   List[Any]      =       os.environ[key]
     except KeyError:
          # KEY isn't set, default to `default`.
          lowercase__    :   List[str]      =       default
     else:
          # KEY is set, convert it to True or False.
          try:
               lowercase__    :   List[Any]      =       strtobool(SCREAMING_SNAKE_CASE_			)
          except ValueError:
               # More values are supported, but let's keep the message simple.
               raise ValueError(f"""If set, {key} must be yes or no."""			)
     return _value


snake_case_			  = parse_flag_from_env('''RUN_SLOW''', default=False)
snake_case_			  = parse_flag_from_env('''RUN_REMOTE''', default=False)
snake_case_			  = parse_flag_from_env('''RUN_LOCAL''', default=True)
snake_case_			  = parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
snake_case_			  = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
snake_case_			  = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
snake_case_			  = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
snake_case_			  = pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''),
    reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''',
)

# Beam
snake_case_			  = pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''),
    reason='''test requires apache-beam and a compatible dill version''',
)

# Dill-cloudpickle compatibility
snake_case_			  = pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

# Windows
snake_case_			  = pytest.mark.skipif(
    sys.platform == '''win32''',
    reason='''test should not be run on Windows''',
)

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Optional[Any]			):



     '''simple docstring'''





     try:
          import faiss  # noqa
     except ImportError:
          lowercase__    :   Optional[int]      =       unittest.skip('test requires faiss'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Any			):



     '''simple docstring'''





     try:
          import regex  # noqa
     except ImportError:
          lowercase__    :   Optional[Any]      =       unittest.skip('test requires regex'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Optional[Any]			):



     '''simple docstring'''





     try:
          import elasticsearch  # noqa
     except ImportError:
          lowercase__    :   str      =       unittest.skip('test requires elasticsearch'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Tuple			):



     '''simple docstring'''





     try:
          import sqlalchemy  # noqa
     except ImportError:
          lowercase__    :   Optional[Any]      =       unittest.skip('test requires sqlalchemy'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Union[str, Any]			):



     '''simple docstring'''





     if not config.TORCH_AVAILABLE:
          lowercase__    :   Any      =       unittest.skip('test requires PyTorch'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Tuple			):



     '''simple docstring'''





     if not config.TF_AVAILABLE:
          lowercase__    :   List[Any]      =       unittest.skip('test requires TensorFlow'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Union[str, Any]			):



     '''simple docstring'''





     if not config.JAX_AVAILABLE:
          lowercase__    :   Dict      =       unittest.skip('test requires JAX'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Optional[Any]			):



     '''simple docstring'''





     if not config.PIL_AVAILABLE:
          lowercase__    :   str      =       unittest.skip('test requires Pillow'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Any			):



     '''simple docstring'''





     try:
          import transformers  # noqa F401
     except ImportError:
          return unittest.skip('test requires transformers'			)(SCREAMING_SNAKE_CASE_			)
     else:
          return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    str			):



     '''simple docstring'''





     try:
          import tiktoken  # noqa F401
     except ImportError:
          return unittest.skip('test requires tiktoken'			)(SCREAMING_SNAKE_CASE_			)
     else:
          return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Optional[int]			):



     '''simple docstring'''





     try:
          import spacy  # noqa F401
     except ImportError:
          return unittest.skip('test requires spacy'			)(SCREAMING_SNAKE_CASE_			)
     else:
          return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Dict			):



     '''simple docstring'''





     def _require_spacy_model(SCREAMING_SNAKE_CASE_		:    Optional[int]			):
          try:
               import spacy  # noqa F401

               spacy.load(SCREAMING_SNAKE_CASE_			)
          except ImportError:
               return unittest.skip('test requires spacy'			)(SCREAMING_SNAKE_CASE_			)
          except OSError:
               return unittest.skip('test requires spacy model \'{}\''.format(SCREAMING_SNAKE_CASE_			)			)(SCREAMING_SNAKE_CASE_			)
          else:
               return test_case

     return _require_spacy_model

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    int			):



     '''simple docstring'''





     try:
          import pyspark  # noqa F401
     except ImportError:
          return unittest.skip('test requires pyspark'			)(SCREAMING_SNAKE_CASE_			)
     else:
          return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    int			):



     '''simple docstring'''





     try:
          import joblibspark  # noqa F401
     except ImportError:
          return unittest.skip('test requires joblibspark'			)(SCREAMING_SNAKE_CASE_			)
     else:
          return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    List[Any]			):



     '''simple docstring'''





     if not _run_slow_tests or _run_slow_tests == 0:
          lowercase__    :   Dict      =       unittest.skip('test is slow'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Tuple			):



     '''simple docstring'''





     if not _run_local_tests or _run_local_tests == 0:
          lowercase__    :   Tuple      =       unittest.skip('test is local'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Tuple			):



     '''simple docstring'''





     if not _run_packaged_tests or _run_packaged_tests == 0:
          lowercase__    :   List[str]      =       unittest.skip('test is packaged'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Tuple			):



     '''simple docstring'''





     if not _run_remote_tests or _run_remote_tests == 0:
          lowercase__    :   Union[str, Any]      =       unittest.skip('test requires remote'			)(SCREAMING_SNAKE_CASE_			)
     return test_case

def 	snake_case__			(    *SCREAMING_SNAKE_CASE_		:    str			):



     '''simple docstring'''





     def decorate(cls		:    Optional[int]			):
          for name, fn in cls.__dict__.items():
               if callable(SCREAMING_SNAKE_CASE_			) and name.startswith('test'			):
                    for decorator in decorators:
                         lowercase__    :   Union[str, Any]      =       decorator(SCREAMING_SNAKE_CASE_			)
                    setattr(cls	,     SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)
          return cls

     return decorate


class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    pass



class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       Any														=     0
    __lowerCamelCase						:       Dict														=     1
    __lowerCamelCase						:       List[Any]														=     2



@contextmanager
def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Any=OfflineSimulationMode.CONNECTION_FAILS	,     SCREAMING_SNAKE_CASE_		:    Optional[int]=1E-16			):



     '''simple docstring'''





     lowercase__    :   Optional[int]      =       requests.Session().request

     def timeout_request(SCREAMING_SNAKE_CASE_		:    int	,     SCREAMING_SNAKE_CASE_		:    List[str]	,     SCREAMING_SNAKE_CASE_		:    Tuple	,     **SCREAMING_SNAKE_CASE_		:    Dict			):
          # Change the url to an invalid url so that the connection hangs
          lowercase__    :   List[str]      =       'https://10.255.255.1'
          if kwargs.get('timeout'			) is None:
               raise RequestWouldHangIndefinitelyError(
                   f"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout."""			)
          lowercase__    :   Optional[int]      =       timeout
          try:
               return online_request(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     **SCREAMING_SNAKE_CASE_			)
          except Exception as e:
               # The following changes in the error are just here to make the offline timeout error prettier
               lowercase__    :   Union[str, Any]      =       url
               lowercase__    :   Optional[Any]      =       e.args[0]
               lowercase__    :   List[Any]      =       (max_retry_error.args[0].replace('10.255.255.1'	,     f"""OfflineMock[{url}]"""			),)
               lowercase__    :   Tuple      =       (max_retry_error,)
               raise

     def raise_connection_error(SCREAMING_SNAKE_CASE_		:    str	,     SCREAMING_SNAKE_CASE_		:    Union[str, Any]	,     **SCREAMING_SNAKE_CASE_		:    List[Any]			):
          raise requests.ConnectionError('Offline mode is enabled.'	,     request=SCREAMING_SNAKE_CASE_			)

     if mode is OfflineSimulationMode.CONNECTION_FAILS:
          with patch('requests.Session.send'	,     SCREAMING_SNAKE_CASE_			):
               yield
     elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
          # inspired from https://stackoverflow.com/a/904609
          with patch('requests.Session.request'	,     SCREAMING_SNAKE_CASE_			):
               yield
     elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
          with patch('datasets.config.HF_DATASETS_OFFLINE'	,     SCREAMING_SNAKE_CASE_			):
               yield
     else:
          raise ValueError('Please use a value from the OfflineSimulationMode enum.'			)

@contextmanager
def 	snake_case__			(    *SCREAMING_SNAKE_CASE_		:    List[Any]	,     **SCREAMING_SNAKE_CASE_		:    Tuple			):



     '''simple docstring'''





     lowercase__    :   str      =       str(Path().resolve()			)
     with tempfile.TemporaryDirectory(*SCREAMING_SNAKE_CASE_	,     **SCREAMING_SNAKE_CASE_			) as tmp_dir:
          try:
               os.chdir(SCREAMING_SNAKE_CASE_			)
               yield
          finally:
               os.chdir(SCREAMING_SNAKE_CASE_			)

@contextmanager
def 	snake_case__			(    ):



     '''simple docstring'''





     import gc

     gc.collect()
     lowercase__    :   str      =       pa.total_allocated_bytes()
     yield
     assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."

@contextmanager
def 	snake_case__			(    ):



     '''simple docstring'''





     import gc

     gc.collect()
     lowercase__    :   Optional[int]      =       pa.total_allocated_bytes()
     yield
     assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    List[Any]	,     SCREAMING_SNAKE_CASE_		:    int			):



     '''simple docstring'''





     return deepcopy(SCREAMING_SNAKE_CASE_			).integers(0	,     100	,     10			).tolist() == deepcopy(SCREAMING_SNAKE_CASE_			).integers(0	,     100	,     10			).tolist()

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Dict			):



     '''simple docstring'''





     import decorator
     from requests.exceptions import HTTPError

     def _wrapper(SCREAMING_SNAKE_CASE_		:    List[Any]	,     *SCREAMING_SNAKE_CASE_		:    Optional[int]	,     **SCREAMING_SNAKE_CASE_		:    str			):
          try:
               return func(*SCREAMING_SNAKE_CASE_	,     **SCREAMING_SNAKE_CASE_			)
          except HTTPError as err:
               if str(SCREAMING_SNAKE_CASE_			).startswith('500'			) or str(SCREAMING_SNAKE_CASE_			).startswith('502'			):
                    pytest.xfail(str(SCREAMING_SNAKE_CASE_			)			)
               raise err

     return decorator.decorator(_wrapper	,     SCREAMING_SNAKE_CASE_			)


class       SCREAMING_SNAKE_CASE__					:





    def __init__(      self						,   a						,   a						,   a):
         lowercase__    :   List[Any]      =       returncode
         lowercase__    :   str      =       stdout
         lowercase__    :   Optional[Any]      =       stderr



async def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Union[str, Any]	,     SCREAMING_SNAKE_CASE_		:    List[Any]			):



     '''simple docstring'''





     while True:
          lowercase__    :   Optional[int]      =       await stream.readline()
          if line:
               callback(SCREAMING_SNAKE_CASE_			)
          else:
               break

async def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Union[str, Any]	,     SCREAMING_SNAKE_CASE_		:    Any=None	,     SCREAMING_SNAKE_CASE_		:    Optional[Any]=None	,     SCREAMING_SNAKE_CASE_		:    Dict=None	,     SCREAMING_SNAKE_CASE_		:    Optional[int]=False	,     SCREAMING_SNAKE_CASE_		:    List[str]=False			):



     '''simple docstring'''





     if echo:
          print('\nRunning: '	,     ' '.join(SCREAMING_SNAKE_CASE_			)			)

     lowercase__    :   Tuple      =       await asyncio.create_subprocess_exec(
         cmd[0]	,     *cmd[1:]	,     stdin=SCREAMING_SNAKE_CASE_	,     stdout=asyncio.subprocess.PIPE	,     stderr=asyncio.subprocess.PIPE	,     env=SCREAMING_SNAKE_CASE_	,     )

     # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
     # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
     #
     # If it starts hanging, will need to switch to the following code. The problem is that no data
     # will be seen until it's done and if it hangs for example there will be no debug info.
     # out, err = await p.communicate()
     # return _RunOutput(p.returncode, out, err)

     lowercase__    :   Union[str, Any]      =       []
     lowercase__    :   List[str]      =       []

     def tee(SCREAMING_SNAKE_CASE_		:    Tuple	,     SCREAMING_SNAKE_CASE_		:    int	,     SCREAMING_SNAKE_CASE_		:    Optional[int]	,     SCREAMING_SNAKE_CASE_		:    str=""			):
          lowercase__    :   Tuple      =       line.decode('utf-8'			).rstrip()
          sink.append(SCREAMING_SNAKE_CASE_			)
          if not quiet:
               print(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     file=SCREAMING_SNAKE_CASE_			)

    # XXX: the timeout doesn't seem to make any difference here
     await asyncio.wait(
         [
             _read_stream(p.stdout	,     lambda SCREAMING_SNAKE_CASE_			: tee(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     sys.stdout	,     label='stdout:'			)			),
             _read_stream(p.stderr	,     lambda SCREAMING_SNAKE_CASE_			: tee(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     sys.stderr	,     label='stderr:'			)			),
         ]	,     timeout=SCREAMING_SNAKE_CASE_	,     )
     return _RunOutput(await p.wait()	,     SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Tuple	,     SCREAMING_SNAKE_CASE_		:    Optional[int]=None	,     SCREAMING_SNAKE_CASE_		:    int=None	,     SCREAMING_SNAKE_CASE_		:    List[str]=180	,     SCREAMING_SNAKE_CASE_		:    str=False	,     SCREAMING_SNAKE_CASE_		:    Optional[int]=True			):



     '''simple docstring'''





     lowercase__    :   Tuple      =       asyncio.get_event_loop()
     lowercase__    :   List[str]      =       loop.run_until_complete(
         _stream_subprocess(SCREAMING_SNAKE_CASE_	,     env=SCREAMING_SNAKE_CASE_	,     stdin=SCREAMING_SNAKE_CASE_	,     timeout=SCREAMING_SNAKE_CASE_	,     quiet=SCREAMING_SNAKE_CASE_	,     echo=SCREAMING_SNAKE_CASE_			)			)

     lowercase__    :   Any      =       ' '.join(SCREAMING_SNAKE_CASE_			)
     if result.returncode > 0:
          lowercase__    :   List[str]      =       '\n'.join(result.stderr			)
          raise RuntimeError(
              f"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
              f"""The combined stderr from workers follows:\n{stderr}"""			)

     # check that the subprocess actually did run and produced some output, should the test rely on
     # the remote side to do the testing
     if not result.stdout and not result.stderr:
          raise RuntimeError(f"""'{cmd_str}' produced no output."""			)

     return result

def 	snake_case__			(    ):



     '''simple docstring'''





     lowercase__    :   Any      =       os.environ.get('PYTEST_XDIST_WORKER'	,     'gw0'			)
     lowercase__    :   List[Any]      =       re.sub(R'^gw'	,     ''	,     SCREAMING_SNAKE_CASE_	,     0	,     re.M			)
     return int(SCREAMING_SNAKE_CASE_			)

def 	snake_case__			(    ):



     '''simple docstring'''





     lowercase__    :   str      =       29_500
     lowercase__    :   Tuple      =       pytest_xdist_worker_id()
     return port + uniq_delta




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


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

snake_case_			  = ['''names''', '''prefix''']
snake_case_			  = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']
snake_case_			  = ['''encoding_errors''', '''on_bad_lines''']
snake_case_			  = ['''date_format''']


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





    def       snake_case_				(      self):
         if self.delimiter is not None:
              lowercase__    :   List[Any]      =       self.delimiter
         if self.column_names is not None:
              lowercase__    :   Optional[int]      =       self.column_names





    @property
    def       snake_case_				(      self):
         lowercase__    :   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()						,   a):
                   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       SCREAMING_SNAKE_CASE__					(datasets.ArrowBasedBuilder     ):
    __lowerCamelCase						:       Optional[Any]														=     CsvConfig





    def       snake_case_				(      self):
         return datasets.DatasetInfo(features=self.config.features)





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





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





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

