


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


__lowerCAmelCase	: Dict  				=parse_flag_from_env('RUN_SLOW', default=False)


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skip('''Test was skipped'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(_run_slow_tests    ,       '''test is slow'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(not torch.cuda.is_available()    ,       '''test requires only a CPU'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(torch.cuda.is_available()    ,       '''test requires a GPU'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(is_xpu_available()    ,       '''test requires a XPU'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(is_mps_available()    ,       '''test requires a `mps` backend support in `torch`'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(
						    is_transformers_available() and is_datasets_available()    ,       '''test requires the Hugging Face suite'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(is_bnb_available()    ,       '''test requires the bitsandbytes library'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(is_tpu_available()    ,       '''test requires TPU'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(torch.cuda.device_count() == 1    ,       '''test requires a GPU'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(torch.xpu.device_count() == 1    ,       '''test requires a XPU'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(torch.cuda.device_count() > 1    ,       '''test requires multiple GPUs'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(torch.xpu.device_count() > 1    ,       '''test requires multiple XPUs'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(is_safetensors_available()    ,       '''test requires safetensors'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(is_deepspeed_available()    ,       '''test requires DeepSpeed'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(is_torch_version('''>='''    ,       '''1.12.0'''      )    ,       '''test requires torch version >= 1.12.0'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__=None    ,       lowercase__=None      ):
						if test_case is None:
												return partial(lowercase__    ,       version=lowercase__      )
						return unittest.skipUnless(is_torch_version('''>='''    ,       lowercase__      )    ,       F'''test requires torch version >= {version}'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(is_tensorboard_available()    ,       '''test requires Tensorboard'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(is_wandb_available()    ,       '''test requires wandb'''      )(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(is_comet_ml_available()    ,       '''test requires comet_ml'''      )(lowercase__      )


__lowerCAmelCase	: Optional[Any]  				=(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)


def        _UpperCamelCase							(      lowercase__      ):
						return unittest.skipUnless(
						    _atleast_one_tracker_available    ,       '''test requires at least one tracker to be available and for `comet_ml` to not be installed'''    ,       )(lowercase__      )
class        _lowercase      (			unittest.TestCase       ):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE__				:			Dict						=		True


				@classmethod
				def 		__magic_name__(       cls			:Optional[Any]	)		->			List[Any]:
										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		tempfile.mkdtemp()


				@classmethod
				def 		__magic_name__(       cls			:List[Any]	)		->			List[str]:
										if os.path.exists(cls.tmpdir	):
																shutil.rmtree(cls.tmpdir	)



				def 		__magic_name__(       self			:List[Any]	)		->			List[str]:
										if self.clear_on_setup:
																for path in Path(self.tmpdir	).glob('''**/*'''	):
																						if path.is_file():
																												path.unlink()
																						elif path.is_dir():
																												shutil.rmtree(lowerCAmelCase__	)




class        _lowercase      (			unittest.TestCase       ):






				'''simple docstring'''



				def 		__magic_name__(       self			:List[str]	)		->			Any:
										super().tearDown()
										# Reset the state of the AcceleratorState singleton.
										AcceleratorState._reset_state()
										PartialState._reset_state()




class        _lowercase      (			unittest.TestCase       ):






				'''simple docstring'''



				def 		__magic_name__(       self			:str			,			lowerCAmelCase__			:Union[mock.Mock, List[mock.Mock]]	)		->			Tuple:
										__SCREAMING_SNAKE_CASE						:     List[str]					=		mocks if isinstance(lowerCAmelCase__			,			(tuple, list)	) else [mocks]
										for m in self.mocks:
																m.start()
																self.addCleanup(m.stop	)




def        _UpperCamelCase							(      lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     int					=		AcceleratorState()
						__SCREAMING_SNAKE_CASE						:     Optional[int]					=		tensor[None].clone().to(state.device      )
						__SCREAMING_SNAKE_CASE						:     List[str]					=		gather(lowercase__      ).cpu()
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		tensor[0].cpu()
						for i in range(tensors.shape[0]      ):
												if not torch.equal(tensors[i]    ,       lowercase__      ):
																		return False
						return True
class        _lowercase      :






				'''simple docstring'''



				def __init__(       self			:Union[str, Any]			,			lowerCAmelCase__			:int			,			lowerCAmelCase__			:int			,			lowerCAmelCase__			:str	)		->			List[str]:
										__SCREAMING_SNAKE_CASE						:     List[str]					=		returncode
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		stdout
										__SCREAMING_SNAKE_CASE						:     Dict					=		stderr




async def        _UpperCamelCase							(      lowercase__    ,       lowercase__      ):
						while True:
												__SCREAMING_SNAKE_CASE						:     Tuple					=		await stream.readline()
												if line:
																		callback(lowercase__      )
												else:
																		break


async def        _UpperCamelCase							(      lowercase__    ,       lowercase__=None    ,       lowercase__=None    ,       lowercase__=None    ,       lowercase__=False    ,       lowercase__=False      ):
						if echo:
												print('''\nRunning: '''    ,       ''' '''.join(lowercase__      )      )

						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		await asyncio.create_subprocess_exec(
						    cmd[0]    ,       *cmd[1:]    ,       stdin=lowercase__    ,       stdout=asyncio.subprocess.PIPE    ,       stderr=asyncio.subprocess.PIPE    ,       env=lowercase__    ,       )

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

						__SCREAMING_SNAKE_CASE						:     Tuple					=		[]
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		[]

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

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


def        _UpperCamelCase							(      lowercase__    ,       lowercase__=None    ,       lowercase__=None    ,       lowercase__=180    ,       lowercase__=False    ,       lowercase__=True      ):
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		asyncio.get_event_loop()
						__SCREAMING_SNAKE_CASE						:     Dict					=		loop.run_until_complete(
						    _stream_subprocess(lowercase__    ,       env=lowercase__    ,       stdin=lowercase__    ,       timeout=lowercase__    ,       quiet=lowercase__    ,       echo=lowercase__      )      )

						__SCREAMING_SNAKE_CASE						:     Optional[int]					=		''' '''.join(lowercase__      )
						if result.returncode > 0:
												__SCREAMING_SNAKE_CASE						:     int					=		'''\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        _lowercase      (			A__       ):






				'''simple docstring'''



				pass




def        _UpperCamelCase							(      lowercase__    ,       lowercase__=False      ):
						try:
												__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		subprocess.check_output(lowercase__    ,       stderr=subprocess.STDOUT      )
												if return_stdout:
																		if hasattr(lowercase__    ,       '''decode'''      ):
																								__SCREAMING_SNAKE_CASE						:     List[str]					=		output.decode('''utf-8'''      )
																		return output
						except subprocess.CalledProcessError as e:
												raise SubprocessCallException(
												    F'''Command `{' '.join(lowercase__      )}` failed with the following error:\n\n{e.output.decode()}'''      ) from e




from typing import Optional

from .. import Features, NamedSplit
from ..packaged_modules.text.text import Text
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
class        _lowercase      (			A__       ):






				'''simple docstring'''



				def __init__(       self			:int			,			lowerCAmelCase__			:NestedDataStructureLike[PathLike]			,			lowerCAmelCase__			:Optional[NamedSplit] = None			,			lowerCAmelCase__			:Optional[Features] = None			,			lowerCAmelCase__			:str = None			,			lowerCAmelCase__			:bool = False			,			lowerCAmelCase__			:bool = False			,			lowerCAmelCase__			:Optional[int] = None			,			**lowerCAmelCase__			:Optional[int]			,			)		->			Tuple:
										super().__init__(
										    lowerCAmelCase__			,			split=lowerCAmelCase__			,			features=lowerCAmelCase__			,			cache_dir=lowerCAmelCase__			,			keep_in_memory=lowerCAmelCase__			,			streaming=lowerCAmelCase__			,			num_proc=lowerCAmelCase__			,			**lowerCAmelCase__			,			)
										__SCREAMING_SNAKE_CASE						:     List[str]					=		path_or_paths if isinstance(lowerCAmelCase__			,			lowerCAmelCase__	) else {self.split: path_or_paths}
										__SCREAMING_SNAKE_CASE						:     int					=		Text(
										    cache_dir=lowerCAmelCase__			,			data_files=lowerCAmelCase__			,			features=lowerCAmelCase__			,			**lowerCAmelCase__			,			)



				def 		__magic_name__(       self			:Dict	)		->			Tuple:
										# Build iterable dataset
										if self.streaming:
																__SCREAMING_SNAKE_CASE						:     int					=		self.builder.as_streaming_dataset(split=self.split	)
										# Build regular (map-style) dataset
										else:
																__SCREAMING_SNAKE_CASE						:     List[str]					=		None
																__SCREAMING_SNAKE_CASE						:     str					=		None
																__SCREAMING_SNAKE_CASE						:     Dict					=		None
																__SCREAMING_SNAKE_CASE						:     Tuple					=		None

																self.builder.download_and_prepare(
																    download_config=lowerCAmelCase__			,			download_mode=lowerCAmelCase__			,			verification_mode=lowerCAmelCase__			,			base_path=lowerCAmelCase__			,			num_proc=self.num_proc			,			)
																__SCREAMING_SNAKE_CASE						:     Optional[int]					=		self.builder.as_dataset(
																    split=self.split			,			verification_mode=lowerCAmelCase__			,			in_memory=self.keep_in_memory	)
										return dataset
