






import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
def      a_ (      _A      ,   _A=False  )			->			List[str]:







				"""simple docstring"""
				try:
								snake_case__									=     os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								snake_case__									=     default
				else:
								# KEY is set, convert it to True or False.
								try:
												snake_case__									=     strtobool(_A  )
								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


__UpperCamelCase					:		Any	  =						parse_flag_from_env("""RUN_SLOW""", default=False)
def      a_ (      _A  )			->			str:







				"""simple docstring"""
				return unittest.skip('Test was skipped'  )(_A  )
def      a_ (      _A  )			->			int:







				"""simple docstring"""
				return unittest.skipUnless(_run_slow_tests      ,   'test is slow'  )(_A  )
def      a_ (      _A  )			->			int:







				"""simple docstring"""
				return unittest.skipUnless(not torch.cuda.is_available()      ,   'test requires only a CPU'  )(_A  )
def      a_ (      _A  )			->			Optional[Any]:







				"""simple docstring"""
				return unittest.skipUnless(torch.cuda.is_available()      ,   'test requires a GPU'  )(_A  )
def      a_ (      _A  )			->			Any:







				"""simple docstring"""
				return unittest.skipUnless(is_xpu_available()      ,   'test requires a XPU'  )(_A  )
def      a_ (      _A  )			->			List[Any]:







				"""simple docstring"""
				return unittest.skipUnless(is_mps_available()      ,   'test requires a `mps` backend support in `torch`'  )(_A  )
def      a_ (      _A  )			->			Optional[Any]:







				"""simple docstring"""
				return unittest.skipUnless(
				    is_transformers_available() and is_datasets_available()      ,   'test requires the Hugging Face suite'  )(_A  )
def      a_ (      _A  )			->			Tuple:







				"""simple docstring"""
				return unittest.skipUnless(is_bnb_available()      ,   'test requires the bitsandbytes library'  )(_A  )
def      a_ (      _A  )			->			Tuple:







				"""simple docstring"""
				return unittest.skipUnless(is_tpu_available()      ,   'test requires TPU'  )(_A  )
def      a_ (      _A  )			->			Optional[int]:







				"""simple docstring"""
				return unittest.skipUnless(torch.cuda.device_count() == 1      ,   'test requires a GPU'  )(_A  )
def      a_ (      _A  )			->			List[str]:







				"""simple docstring"""
				return unittest.skipUnless(torch.xpu.device_count() == 1      ,   'test requires a XPU'  )(_A  )
def      a_ (      _A  )			->			List[Any]:







				"""simple docstring"""
				return unittest.skipUnless(torch.cuda.device_count() > 1      ,   'test requires multiple GPUs'  )(_A  )
def      a_ (      _A  )			->			Tuple:







				"""simple docstring"""
				return unittest.skipUnless(torch.xpu.device_count() > 1      ,   'test requires multiple XPUs'  )(_A  )
def      a_ (      _A  )			->			Union[str, Any]:







				"""simple docstring"""
				return unittest.skipUnless(is_safetensors_available()      ,   'test requires safetensors'  )(_A  )
def      a_ (      _A  )			->			Dict:







				"""simple docstring"""
				return unittest.skipUnless(is_deepspeed_available()      ,   'test requires DeepSpeed'  )(_A  )
def      a_ (      _A  )			->			List[Any]:







				"""simple docstring"""
				return unittest.skipUnless(is_torch_version('>='      ,   '1.12.0'  )      ,   'test requires torch version >= 1.12.0'  )(_A  )
def      a_ (      _A=None      ,   _A=None  )			->			Union[str, Any]:







				"""simple docstring"""
				if test_case is None:
								return partial(_A      ,   version=_A  )
				return unittest.skipUnless(is_torch_version('>='      ,   _A  )      ,   f'''test requires torch version >= {version}'''  )(_A  )
def      a_ (      _A  )			->			str:







				"""simple docstring"""
				return unittest.skipUnless(is_tensorboard_available()      ,   'test requires Tensorboard'  )(_A  )
def      a_ (      _A  )			->			List[str]:







				"""simple docstring"""
				return unittest.skipUnless(is_wandb_available()      ,   'test requires wandb'  )(_A  )
def      a_ (      _A  )			->			str:







				"""simple docstring"""
				return unittest.skipUnless(is_comet_ml_available()      ,   'test requires comet_ml'  )(_A  )


__UpperCamelCase					:		str	  =						(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)
def      a_ (      _A  )			->			Dict:







				"""simple docstring"""
				return unittest.skipUnless(
				    _atleast_one_tracker_available      ,   'test requires at least one tracker to be available and for `comet_ml` to not be installed'      ,   )(_A  )


class   __SCREAMING_SNAKE_CASE(	unittest.TestCase	):
							_UpperCAmelCase     =       True
							@classmethod
							def lowerCAmelCase_ (     cls:      str						)		->		int:
											snake_case__									=     tempfile.mkdtemp()
							@classmethod
							def lowerCAmelCase_ (     cls:      List[str]						)		->		List[str]:
											if os.path.exists(cls.tmpdir						):
															shutil.rmtree(cls.tmpdir						)


							def lowerCAmelCase_ (     self:      Dict						)		->		int:
											if self.clear_on_setup:
															for path in Path(self.tmpdir						).glob('**/*'						):
																			if path.is_file():
																							path.unlink()
																			elif path.is_dir():
																							shutil.rmtree(UpperCamelCase						)


class   __SCREAMING_SNAKE_CASE(	unittest.TestCase	):
							def lowerCAmelCase_ (     self:      List[str]						)		->		List[str]:
											super().tearDown()
											# Reset the state of the AcceleratorState singleton.
											AcceleratorState._reset_state()
											PartialState._reset_state()


class   __SCREAMING_SNAKE_CASE(	unittest.TestCase	):
							def lowerCAmelCase_ (     self:      Union[str, Any]       ,	UpperCamelCase:      Union[mock.Mock, List[mock.Mock]]						)		->		Tuple:
											snake_case__									=     mocks if isinstance(UpperCamelCase       ,	(tuple, list)						) else [mocks]
											for m in self.mocks:
															m.start()
															self.addCleanup(m.stop						)


def      a_ (      _A  )			->			Union[str, Any]:







				"""simple docstring"""
				snake_case__									=     AcceleratorState()
				snake_case__									=     tensor[None].clone().to(state.device  )
				snake_case__									=     gather(_A  ).cpu()
				snake_case__									=     tensor[0].cpu()
				for i in range(tensors.shape[0]  ):
								if not torch.equal(tensors[i]      ,   _A  ):
												return False
				return True


class   __SCREAMING_SNAKE_CASE:
							def __init__(     self:      Optional[Any]       ,	UpperCamelCase:      Tuple       ,	UpperCamelCase:      Dict       ,	UpperCamelCase:      Optional[Any]						)		->		Tuple:
											snake_case__									=     returncode
											snake_case__									=     stdout
											snake_case__									=     stderr


async def      a_ (      _A      ,   _A  )			->			List[Any]:







				"""simple docstring"""
				while True:
								snake_case__									=     await stream.readline()
								if line:
												callback(_A  )
								else:
												break
async def      a_ (      _A      ,   _A=None      ,   _A=None      ,   _A=None      ,   _A=False      ,   _A=False  )			->			_RunOutput:







				"""simple docstring"""
				if echo:
								print('\nRunning: '      ,   ' '.join(_A  )  )

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

				# 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)

				snake_case__									=     []
				snake_case__									=     []

				def tee(_A      ,   _A      ,   _A      ,   _A=""  ):
								snake_case__									=     line.decode('utf-8'  ).rstrip()
								sink.append(_A  )
								if not quiet:
												print(_A      ,   _A      ,   file=_A  )

    # XXX: the timeout doesn't seem to make any difference here
				await asyncio.wait(
				    [
				        asyncio.create_task(_read_stream(p.stdout      ,   lambda _A  : tee(_A      ,   _A      ,   sys.stdout      ,   label='stdout:'  )  )  ),
				        asyncio.create_task(_read_stream(p.stderr      ,   lambda _A  : tee(_A      ,   _A      ,   sys.stderr      ,   label='stderr:'  )  )  ),
				    ]      ,   timeout=_A      ,   )
				return _RunOutput(await p.wait()      ,   _A      ,   _A  )
def      a_ (      _A      ,   _A=None      ,   _A=None      ,   _A=180      ,   _A=False      ,   _A=True  )			->			_RunOutput:







				"""simple docstring"""
				snake_case__									=     asyncio.get_event_loop()
				snake_case__									=     loop.run_until_complete(
				    _stream_subprocess(_A      ,   env=_A      ,   stdin=_A      ,   timeout=_A      ,   quiet=_A      ,   echo=_A  )  )

				snake_case__									=     ' '.join(_A  )
				if result.returncode > 0:
								snake_case__									=     '\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}'''  )

				return result


class   __SCREAMING_SNAKE_CASE(	a_	):
							pass


def      a_ (      _A      ,   _A=False  )			->			Dict:







				"""simple docstring"""
				try:
								snake_case__									=     subprocess.check_output(_A      ,   stderr=subprocess.STDOUT  )
								if return_stdout:
												if hasattr(_A      ,   'decode'  ):
																snake_case__									=     output.decode('utf-8'  )
												return output
				except subprocess.CalledProcessError as e:
								raise SubprocessCallException(
								    f'''Command `{' '.join(_A  )}` failed with the following error:\n\n{e.output.decode()}'''  ) from e












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

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


@dataclass
class   __SCREAMING_SNAKE_CASE(	datasets.BuilderConfig	):
							_UpperCAmelCase     =       ","
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       "infer"
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       "."
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       '"'
							_UpperCAmelCase     =       0
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       0
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       1_0_0_0_0
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       "strict"
							_UpperCAmelCase     =       "error"
							_UpperCAmelCase     =       None
							def lowerCAmelCase_ (     self:      Tuple						)		->		int:
											if self.delimiter is not None:
															snake_case__									=     self.delimiter
											if self.column_names is not None:
															snake_case__									=     self.column_names


							@property
							def lowerCAmelCase_ (     self:      Optional[int]						)		->		List[str]:
											snake_case__									=     {
											    '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()       ,	UpperCamelCase						):
																			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	):
							_UpperCAmelCase     =       CsvConfig
							def lowerCAmelCase_ (     self:      str						)		->		int:
											return datasets.DatasetInfo(features=self.config.features						)
							def lowerCAmelCase_ (     self:      Tuple       ,	UpperCamelCase:      Dict						)		->		int:
											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__									=     dl_manager.download_and_extract(self.config.data_files						)
											if isinstance(UpperCamelCase       ,	(str, list, tuple)						):
															snake_case__									=     data_files
															if isinstance(UpperCamelCase       ,	UpperCamelCase						):
																			snake_case__									=     [files]
															snake_case__									=     [dl_manager.iter_files(UpperCamelCase						) for file in files]
															return [datasets.SplitGenerator(name=datasets.Split.TRAIN       ,	gen_kwargs={'files': files}						)]
											snake_case__									=     []
											for split_name, files in data_files.items():
															if isinstance(UpperCamelCase       ,	UpperCamelCase						):
																			snake_case__									=     [files]
															snake_case__									=     [dl_manager.iter_files(UpperCamelCase						) for file in files]
															splits.append(datasets.SplitGenerator(name=UpperCamelCase       ,	gen_kwargs={'files': files}						)						)
											return splits
							def lowerCAmelCase_ (     self:      int       ,	UpperCamelCase:      pa.Table						)		->		pa.Table:
											if self.config.features is not None:
															snake_case__									=     self.config.features.arrow_schema
															if all(not require_storage_cast(UpperCamelCase						) for feature in self.config.features.values()						):
																			# cheaper cast
																			snake_case__									=     pa.Table.from_arrays([pa_table[field.name] for field in schema]       ,	schema=UpperCamelCase						)
															else:
																			# more expensive cast; allows str <-> int/float or str to Audio for example
																			snake_case__									=     table_cast(UpperCamelCase       ,	UpperCamelCase						)
											return pa_table


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




