





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 					lowerCAmelCase__(		lowercase				:			List[Any]      ,   lowercase				:			Tuple=False )       ->			int:


  try:
    __snake_case      : Union[str, Any]						=				os.environ[key]
  except KeyError:
    # KEY isn't set, default to `default`.
    __snake_case      : Any						=				default
  else:
    # KEY is set, convert it to True or False.
    try:
      __snake_case      : List[Any]						=				strtobool(UpperCamelCase_ )
    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				=       parse_flag_from_env('''RUN_SLOW''', default=False)







def 					lowerCAmelCase__(		lowercase				:			int )       ->			Optional[int]:
  return unittest.skip("Test was skipped" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Any )       ->			Optional[int]:
  return unittest.skipUnless(_run_slow_tests      ,   "test is slow" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Tuple )       ->			List[Any]:
  return unittest.skipUnless(not torch.cuda.is_available()      ,   "test requires only a CPU" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			int )       ->			Any:
  return unittest.skipUnless(torch.cuda.is_available()      ,   "test requires a GPU" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Optional[int] )       ->			Tuple:
  return unittest.skipUnless(is_xpu_available()      ,   "test requires a XPU" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Optional[int] )       ->			Dict:
  return unittest.skipUnless(is_mps_available()      ,   "test requires a `mps` backend support in `torch`" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			int )       ->			List[Any]:
  return unittest.skipUnless(
      is_transformers_available() and is_datasets_available()      ,   "test requires the Hugging Face suite" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Union[str, Any] )       ->			Tuple:
  return unittest.skipUnless(is_bnb_available()      ,   "test requires the bitsandbytes library" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Optional[Any] )       ->			int:
  return unittest.skipUnless(is_tpu_available()      ,   "test requires TPU" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			str )       ->			List[Any]:
  return unittest.skipUnless(torch.cuda.device_count() == 1      ,   "test requires a GPU" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Union[str, Any] )       ->			List[str]:
  return unittest.skipUnless(torch.xpu.device_count() == 1      ,   "test requires a XPU" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			List[Any] )       ->			str:
  return unittest.skipUnless(torch.cuda.device_count() > 1      ,   "test requires multiple GPUs" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Optional[int] )       ->			str:
  return unittest.skipUnless(torch.xpu.device_count() > 1      ,   "test requires multiple XPUs" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			str )       ->			int:
  return unittest.skipUnless(is_safetensors_available()      ,   "test requires safetensors" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Dict )       ->			str:
  return unittest.skipUnless(is_deepspeed_available()      ,   "test requires DeepSpeed" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			List[str] )       ->			Dict:
  return unittest.skipUnless(is_torch_version(">="      ,   "1.12.0" )      ,   "test requires torch version >= 1.12.0" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Dict=None      ,   lowercase				:			int=None )       ->			int:


  if test_case is None:
    return partial(UpperCamelCase_      ,   version=UpperCamelCase_ )
  return unittest.skipUnless(is_torch_version(">="      ,   UpperCamelCase_ )      ,   f"""test requires torch version >= {version}""" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			List[Any] )       ->			Any:
  return unittest.skipUnless(is_tensorboard_available()      ,   "test requires Tensorboard" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Optional[Any] )       ->			Union[str, Any]:
  return unittest.skipUnless(is_wandb_available()      ,   "test requires wandb" )(UpperCamelCase_ )







def 					lowerCAmelCase__(		lowercase				:			Optional[int] )       ->			Tuple:
  return unittest.skipUnless(is_comet_ml_available()      ,   "test requires comet_ml" )(UpperCamelCase_ )


_UpperCamelCase				=       (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)







def 					lowerCAmelCase__(		lowercase				:			List[str] )       ->			str:
  return unittest.skipUnless(
      _atleast_one_tracker_available      ,   "test requires at least one tracker to be available and for `comet_ml` to not be installed"      ,   )(UpperCamelCase_ )




class  _lowerCamelCase       (			unittest.TestCase			):



      """simple docstring"""






      UpperCAmelCase_  :					Tuple      			=True







      @classmethod
      def   UpperCAmelCase						(       cls      )				->      str:






        '''simple docstring'''






        __snake_case      : str						=				tempfile.mkdtemp()







      @classmethod
      def   UpperCAmelCase						(       cls      )				->      int:






        '''simple docstring'''






        if os.path.exists(cls.tmpdir      ):
          shutil.rmtree(cls.tmpdir      )







      def   UpperCAmelCase						(       self      )				->      str:






        '''simple docstring'''






        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  _lowerCamelCase       (			unittest.TestCase			):



      """simple docstring"""






      def   UpperCAmelCase						(       self      )				->      str:






        '''simple docstring'''






        super().tearDown()
        # Reset the state of the AcceleratorState singleton.
        AcceleratorState._reset_state()
        PartialState._reset_state()




class  _lowerCamelCase       (			unittest.TestCase			):



      """simple docstring"""






      def   UpperCAmelCase						(       self ,  UpperCAmelCase      )				->      List[Any]:






        '''simple docstring'''






        __snake_case      : Any						=				mocks if isinstance(UpperCAmelCase__ ,  (tuple, list)      ) else [mocks]
        for m in self.mocks:
          m.start()
          self.addCleanup(m.stop      )







def 					lowerCAmelCase__(		lowercase				:			int )       ->			int:
  __snake_case      : Tuple						=				AcceleratorState()
  __snake_case      : Optional[Any]						=				tensor[None].clone().to(state.device )
  __snake_case      : Dict						=				gather(UpperCamelCase_ ).cpu()
  __snake_case      : Optional[int]						=				tensor[0].cpu()
  for i in range(tensors.shape[0] ):
    if not torch.equal(tensors[i]      ,   UpperCamelCase_ ):
      return False
  return True




class  _lowerCamelCase       :



      """simple docstring"""






      def __init__(       self ,  UpperCAmelCase ,  UpperCAmelCase ,  UpperCAmelCase      )				->      Any:






        '''simple docstring'''






        __snake_case      : Optional[int]						=				returncode
        __snake_case      : Optional[int]						=				stdout
        __snake_case      : List[Any]						=				stderr







async def 					lowerCAmelCase__(		lowercase				:			int      ,   lowercase				:			List[str] )       ->			Any:


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







async def 					lowerCAmelCase__(		lowercase				:			Optional[int]      ,   lowercase				:			List[str]=None      ,   lowercase				:			Optional[Any]=None      ,   lowercase				:			List[str]=None      ,   lowercase				:			Dict=False      ,   lowercase				:			int=False )       ->			_RunOutput:


  if echo:
    print("\nRunning: "      ,   " ".join(UpperCamelCase_ ) )

  __snake_case      : Optional[int]						=				await asyncio.create_subprocess_exec(
      cmd[0]      ,   *cmd[1:]      ,   stdin=UpperCamelCase_      ,   stdout=asyncio.subprocess.PIPE      ,   stderr=asyncio.subprocess.PIPE      ,   env=UpperCamelCase_      ,   )

  # 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      : Any						=				[]
  __snake_case      : int						=				[]

  def tee(lowercase				:			Any      ,   lowercase				:			List[Any]      ,   lowercase				:			Dict      ,   lowercase				:			int="" ):
    __snake_case      : str						=				line.decode("utf-8" ).rstrip()
    sink.append(UpperCamelCase_ )
    if not quiet:
      print(UpperCamelCase_      ,   UpperCamelCase_      ,   file=UpperCamelCase_ )

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







def 					lowerCAmelCase__(		lowercase				:			str      ,   lowercase				:			Optional[Any]=None      ,   lowercase				:			Dict=None      ,   lowercase				:			str=180      ,   lowercase				:			Optional[int]=False      ,   lowercase				:			int=True )       ->			_RunOutput:
  __snake_case      : Optional[int]						=				asyncio.get_event_loop()
  __snake_case      : int						=				loop.run_until_complete(
      _stream_subprocess(UpperCamelCase_      ,   env=UpperCamelCase_      ,   stdin=UpperCamelCase_      ,   timeout=UpperCamelCase_      ,   quiet=UpperCamelCase_      ,   echo=UpperCamelCase_ ) )

  __snake_case      : int						=				" ".join(UpperCamelCase_ )
  if result.returncode > 0:
    __snake_case      : List[Any]						=				"\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  _lowerCamelCase       (			a			):



      """simple docstring"""






      pass







def 					lowerCAmelCase__(		lowercase				:			List[str]      ,   lowercase				:			Optional[int]=False )       ->			Union[str, Any]:


  try:
    __snake_case      : Any						=				subprocess.check_output(UpperCamelCase_      ,   stderr=subprocess.STDOUT )
    if return_stdout:
      if hasattr(UpperCamelCase_      ,   "decode" ):
        __snake_case      : Optional[Any]						=				output.decode("utf-8" )
      return output
  except subprocess.CalledProcessError as e:
    raise SubprocessCallException(
        f"""Command `{" ".join(UpperCamelCase_ )}` failed with the following error:\n\n{e.output.decode()}""" ) from e




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


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

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




@dataclass
class 					_lowerCAmelCase  (	datasets.BuilderConfig   ):







 """simple docstring"""







 __UpperCAmelCase	:					str   		=	","
 __UpperCAmelCase	:					Optional[str]   		=	None
 __UpperCAmelCase	:					Optional[Union[int, List[int], str]]   		=	"infer"
 __UpperCAmelCase	:					Optional[List[str]]   		=	None
 __UpperCAmelCase	:					Optional[List[str]]   		=	None
 __UpperCAmelCase	:					Optional[Union[int, str, List[int], List[str]]]   		=	None
 __UpperCAmelCase	:					Optional[Union[List[int], List[str]]]   		=	None
 __UpperCAmelCase	:					Optional[str]   		=	None
 __UpperCAmelCase	:					bool   		=	True
 __UpperCAmelCase	:					Optional[Literal["c", "python", "pyarrow"]]   		=	None
 __UpperCAmelCase	:					Dict[Union[int, str], Callable[[Any], Any]]   		=	None
 __UpperCAmelCase	:					Optional[list]   		=	None
 __UpperCAmelCase	:					Optional[list]   		=	None
 __UpperCAmelCase	:					bool   		=	False
 __UpperCAmelCase	:					Optional[Union[int, List[int]]]   		=	None
 __UpperCAmelCase	:					Optional[int]   		=	None
 __UpperCAmelCase	:					Optional[Union[str, List[str]]]   		=	None
 __UpperCAmelCase	:					bool   		=	True
 __UpperCAmelCase	:					bool   		=	True
 __UpperCAmelCase	:					bool   		=	False
 __UpperCAmelCase	:					bool   		=	True
 __UpperCAmelCase	:					Optional[str]   		=	None
 __UpperCAmelCase	:					str   		=	"."
 __UpperCAmelCase	:					Optional[str]   		=	None
 __UpperCAmelCase	:					str   		=	'"'
 __UpperCAmelCase	:					int   		=	0
 __UpperCAmelCase	:					Optional[str]   		=	None
 __UpperCAmelCase	:					Optional[str]   		=	None
 __UpperCAmelCase	:					Optional[str]   		=	None
 __UpperCAmelCase	:					Optional[str]   		=	None
 __UpperCAmelCase	:					bool   		=	True
 __UpperCAmelCase	:					bool   		=	True
 __UpperCAmelCase	:					int   		=	0
 __UpperCAmelCase	:					bool   		=	True
 __UpperCAmelCase	:					bool   		=	False
 __UpperCAmelCase	:					Optional[str]   		=	None
 __UpperCAmelCase	:					int   		=	1_0_0_0_0
 __UpperCAmelCase	:					Optional[datasets.Features]   		=	None
 __UpperCAmelCase	:					Optional[str]   		=	"strict"
 __UpperCAmelCase	:					Literal["error", "warn", "skip"]   		=	"error"
 __UpperCAmelCase	:					Optional[str]   		=	None


 def 					_lowercase (			self							:			Tuple	):
    if self.delimiter is not None:
       __lowercase								=						self.delimiter
    if self.column_names is not None:
       __lowercase								=						self.column_names



 @property
 def 					_lowercase (			self							:			Union[str, Any]	):
    __lowercase								=						{
        "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 					_lowerCAmelCase  (	datasets.ArrowBasedBuilder   ):







 """simple docstring"""







 __UpperCAmelCase	:					Tuple   		=	CsvConfig


 def 					_lowercase (			self							:			List[str]	):
    return datasets.DatasetInfo(features=self.config.features	)


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


 def 					_lowercase (			self							:			Dict,					UpperCAmelCase__							:			pa.Table	):
    if self.config.features is not None:
       __lowercase								=						self.config.features.arrow_schema
       if all(not require_storage_cast(UpperCAmelCase__	) for feature in self.config.features.values()	):
          # cheaper cast
          __lowercase								=						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
          __lowercase								=						table_cast(UpperCAmelCase__,					UpperCAmelCase__	)
    return pa_table



 def 					_lowercase (			self							:			Optional[Any],					UpperCAmelCase__							:			List[str]	):
    __lowercase								=						self.config.features.arrow_schema if self.config.features else None
    # dtype allows reading an int column as str
    __lowercase								=						(
        {
            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__	)	):
       __lowercase								=						pd.read_csv(UpperCAmelCase__,					iterator=UpperCAmelCase__,					dtype=UpperCAmelCase__,					**self.config.pd_read_csv_kwargs	)
       try:
          for batch_idx, df in enumerate(UpperCAmelCase__	):
             __lowercase								=						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




