

'''simple docstring'''





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			(   __magic_name__						:     Dict   , __magic_name__						:     Optional[int]=False						)				->  List[Any]:
						try:
												lowercase :							Union[str, Any]    		=os.environ[key]
						except KeyError:
												# KEY isn't set, default to `default`.
												lowercase :							Tuple    		=default
						else:
												# KEY is set, convert it to True or False.
												try:
																		lowercase :							Optional[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			(   __magic_name__						:     Union[str, Any]						)				->  Any:
						return unittest.skip('''Test was skipped'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     List[Any]						)				->  Tuple:
						return unittest.skipUnless(_run_slow_tests   , '''test is slow'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Union[str, Any]						)				->  List[str]:
						return unittest.skipUnless(not torch.cuda.is_available()   , '''test requires only a CPU'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Any						)				->  Optional[int]:
						return unittest.skipUnless(torch.cuda.is_available()   , '''test requires a GPU'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Any						)				->  int:
						return unittest.skipUnless(is_xpu_available()   , '''test requires a XPU'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     List[str]						)				->  Tuple:
						return unittest.skipUnless(is_mps_available()   , '''test requires a `mps` backend support in `torch`'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     str						)				->  Dict:
						return unittest.skipUnless(
						    is_transformers_available() and is_datasets_available()   , '''test requires the Hugging Face suite'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     List[Any]						)				->  Dict:
						return unittest.skipUnless(is_bnb_available()   , '''test requires the bitsandbytes library'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Union[str, Any]						)				->  Optional[int]:
						return unittest.skipUnless(is_tpu_available()   , '''test requires TPU'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Optional[int]						)				->  Union[str, Any]:
						return unittest.skipUnless(torch.cuda.device_count() == 1   , '''test requires a GPU'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     List[Any]						)				->  Union[str, Any]:
						return unittest.skipUnless(torch.xpu.device_count() == 1   , '''test requires a XPU'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     List[str]						)				->  Optional[Any]:
						return unittest.skipUnless(torch.cuda.device_count() > 1   , '''test requires multiple GPUs'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Dict						)				->  Union[str, Any]:
						return unittest.skipUnless(torch.xpu.device_count() > 1   , '''test requires multiple XPUs'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Union[str, Any]						)				->  Union[str, Any]:
						return unittest.skipUnless(is_safetensors_available()   , '''test requires safetensors'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     List[Any]						)				->  Optional[Any]:
						return unittest.skipUnless(is_deepspeed_available()   , '''test requires DeepSpeed'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Dict						)				->  List[str]:
						return unittest.skipUnless(is_torch_version('''>='''   , '''1.12.0'''						)   , '''test requires torch version >= 1.12.0'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Optional[Any]=None   , __magic_name__						:     Optional[Any]=None						)				->  List[str]:
						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			(   __magic_name__						:     List[Any]						)				->  Union[str, Any]:
						return unittest.skipUnless(is_tensorboard_available()   , '''test requires Tensorboard'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Union[str, Any]						)				->  Dict:
						return unittest.skipUnless(is_wandb_available()   , '''test requires wandb'''						)(UpperCAmelCase_						)






def 				_lowerCAmelCase			(   __magic_name__						:     Optional[Any]						)				->  str:
						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			(   __magic_name__						:     List[str]						)				->  Union[str, Any]:
						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 		__SCREAMING_SNAKE_CASE							(			unittest.TestCase      ):
				lowerCamelCase_		       =    True







				@classmethod
				def  lowerCamelCase_	(       cls     :		Optional[Any]   ):
										'''simple docstring'''
										lowercase :							int    		=tempfile.mkdtemp()







				@classmethod
				def  lowerCamelCase_	(       cls     :		Tuple   ):
										'''simple docstring'''
										if os.path.exists(cls.tmpdir   ):
																shutil.rmtree(cls.tmpdir   )







				def  lowerCamelCase_	(       self     :		List[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(__A   )





class 		__SCREAMING_SNAKE_CASE							(			unittest.TestCase      ):







				def  lowerCamelCase_	(       self     :		Optional[Any]   ):
										'''simple docstring'''
										super().tearDown()
										# Reset the state of the AcceleratorState singleton.
										AcceleratorState._reset_state()
										PartialState._reset_state()





class 		__SCREAMING_SNAKE_CASE							(			unittest.TestCase      ):







				def  lowerCamelCase_	(       self     :		Optional[Any]		,					UpperCAmelCase__     :		int   ):
										'''simple docstring'''
										lowercase :							List[str]    		=mocks if isinstance(__A		,					(tuple, list)   ) else [mocks]
										for m in self.mocks:
																m.start()
																self.addCleanup(m.stop   )






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





class 		__SCREAMING_SNAKE_CASE							:







				def __init__(       self     :		Union[str, Any]		,					UpperCAmelCase__     :		List[Any]		,					UpperCAmelCase__     :		List[Any]		,					UpperCAmelCase__     :		str   ):
										'''simple docstring'''
										lowercase :							int    		=returncode
										lowercase :							Optional[Any]    		=stdout
										lowercase :							Tuple    		=stderr






async def 				_lowerCAmelCase			(   __magic_name__						:     Optional[int]   , __magic_name__						:     str						)				->  List[Any]:
						while True:
												lowercase :							int    		=await stream.readline()
												if line:
																		callback(UpperCAmelCase_						)
												else:
																		break






async def 				_lowerCAmelCase			(   __magic_name__						:     str   , __magic_name__						:     Tuple=None   , __magic_name__						:     List[str]=None   , __magic_name__						:     Optional[Any]=None   , __magic_name__						:     int=False   , __magic_name__						:     List[Any]=False						)				->  _RunOutput:
						if echo:
												print('''\nRunning: '''   , ''' '''.join(UpperCAmelCase_						)						)

						lowercase :							str    		=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)

						lowercase :							Tuple    		=[]
						lowercase :							Optional[int]    		=[]

						def tee(__magic_name__						:     Dict   , __magic_name__						:     Tuple   , __magic_name__						:     Optional[Any]   , __magic_name__						:     int=""						):
												lowercase :							Tuple    		=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 __magic_name__						: tee(UpperCAmelCase_   , UpperCAmelCase_   , sys.stdout   , label='''stdout:'''						)						)						),
						        asyncio.create_task(_read_stream(p.stderr   , lambda __magic_name__						: tee(UpperCAmelCase_   , UpperCAmelCase_   , sys.stderr   , label='''stderr:'''						)						)						),
						    ]   , timeout=UpperCAmelCase_   , )
						return _RunOutput(await p.wait()   , UpperCAmelCase_   , UpperCAmelCase_						)






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

						lowercase :							Tuple    		=''' '''.join(UpperCAmelCase_						)
						if result.returncode > 0:
												lowercase :							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 		__SCREAMING_SNAKE_CASE							(			lowercase__      ):
				pass






def 				_lowerCAmelCase			(   __magic_name__						:     List[str]   , __magic_name__						:     List[Any]=False						)				->  Optional[int]:
						try:
												lowercase :							Any    		=subprocess.check_output(UpperCAmelCase_   , stderr=subprocess.STDOUT						)
												if return_stdout:
																		if hasattr(UpperCAmelCase_   , '''decode'''						):
																								lowercase :							List[str]    		=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







import importlib
import os

import fsspec
import pytest
from fsspec import register_implementation
from fsspec.registry import _registry as _fsspec_registry

from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem

from .utils import require_lza, require_zstandard
def 							SCREAMING_SNAKE_CASE_	(					UpperCAmelCase_	:     List[Any]				)			->						Dict:
       assert "mock" in _fsspec_registry
       assert "bz2" in _fsspec_registry
def 							SCREAMING_SNAKE_CASE_	(					)			->						Union[str, Any]:
       assert "mock" not in _fsspec_registry
       assert "bz2" in _fsspec_registry
def 							SCREAMING_SNAKE_CASE_	(					)			->						Dict:
       SCREAMING_SNAKE_CASE_							:				Optional[Any]		='''mock-s3-bucket'''
       SCREAMING_SNAKE_CASE_							:				Any		=f's3://{mock_bucket}'
       SCREAMING_SNAKE_CASE_							:				Dict		=extract_path_from_uri(UpperCAmelCase_				)
       assert dataset_path.startswith('''s3://'''				) is False

       SCREAMING_SNAKE_CASE_							:				Dict		='''./local/path'''
       SCREAMING_SNAKE_CASE_							:				str		=extract_path_from_uri(UpperCAmelCase_				)
       assert dataset_path == new_dataset_path
def 							SCREAMING_SNAKE_CASE_	(					UpperCAmelCase_	:     Union[str, Any]				)			->						List[str]:
       SCREAMING_SNAKE_CASE_							:				Union[str, Any]		=is_remote_filesystem(UpperCAmelCase_				)
       assert is_remote is True

       SCREAMING_SNAKE_CASE_							:				Dict		=fsspec.filesystem('''file'''				)

       SCREAMING_SNAKE_CASE_							:				Optional[int]		=is_remote_filesystem(UpperCAmelCase_				)
       assert is_remote is False
@pytest.mark.parametrize('''compression_fs_class'''			,							UpperCAmelCase_				)
def 							SCREAMING_SNAKE_CASE_	(					UpperCAmelCase_	:     Union[str, Any]			,							UpperCAmelCase_	:     Any			,							UpperCAmelCase_	:     Optional[Any]			,							UpperCAmelCase_	:     Optional[Any]			,							UpperCAmelCase_	:     int			,							UpperCAmelCase_	:     str			,							UpperCAmelCase_	:     Any				)			->						List[Any]:
       SCREAMING_SNAKE_CASE_							:				str		={'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_file, '''bz2''': bza_file, '''lz4''': lza_file}
       SCREAMING_SNAKE_CASE_							:				List[Any]		=input_paths[compression_fs_class.protocol]
       if input_path is None:
              SCREAMING_SNAKE_CASE_							:				List[str]		=f'for \'{compression_fs_class.protocol}\' compression protocol, '
              if compression_fs_class.protocol == "lz4":
                     reason += require_lza.kwargs["reason"]
              elif compression_fs_class.protocol == "zstd":
                     reason += require_zstandard.kwargs["reason"]
              pytest.skip(UpperCAmelCase_				)
       SCREAMING_SNAKE_CASE_							:				Union[str, Any]		=fsspec.filesystem(compression_fs_class.protocol			,							fo=UpperCAmelCase_				)
       assert isinstance(UpperCAmelCase_			,							UpperCAmelCase_				)
       SCREAMING_SNAKE_CASE_							:				str		=os.path.basename(UpperCAmelCase_				)
       SCREAMING_SNAKE_CASE_							:				Optional[Any]		=expected_filename[: expected_filename.rindex('''.'''				)]
       assert fs.glob('''*'''				) == [expected_filename]
       with fs.open(UpperCAmelCase_			,							'''r'''			,							encoding='''utf-8'''				) as f, open(UpperCAmelCase_			,							encoding='''utf-8'''				) as expected_file:
              assert f.read() == expected_file.read()
@pytest.mark.parametrize('''protocol'''			,							['''zip''', '''gzip''']				)
def 							SCREAMING_SNAKE_CASE_	(					UpperCAmelCase_	:     Any			,							UpperCAmelCase_	:     Union[str, Any]			,							UpperCAmelCase_	:     str				)			->						Any:
       SCREAMING_SNAKE_CASE_							:				Tuple		={'''zip''': zip_jsonl_path, '''gzip''': jsonl_gz_path}
       SCREAMING_SNAKE_CASE_							:				List[Any]		=compressed_file_paths[protocol]
       SCREAMING_SNAKE_CASE_							:				str		='''dataset.jsonl'''
       SCREAMING_SNAKE_CASE_							:				Dict		=f'{protocol}://{member_file_path}::{compressed_file_path}'
       SCREAMING_SNAKE_CASE_	,     *SCREAMING_SNAKE_CASE_							:				Dict		=fsspec.get_fs_token_paths(UpperCAmelCase_				)
       assert fs.isfile(UpperCAmelCase_				)
       assert not fs.isfile('''non_existing_''' + member_file_path				)
@pytest.mark.integration
def 							SCREAMING_SNAKE_CASE_	(					UpperCAmelCase_	:     List[str]			,							UpperCAmelCase_	:     Optional[int]			,							UpperCAmelCase_	:     Optional[int]			,							UpperCAmelCase_	:     int				)			->						int:
       SCREAMING_SNAKE_CASE_							:				Dict		=hf_api.dataset_info(UpperCAmelCase_			,							token=UpperCAmelCase_				)
       SCREAMING_SNAKE_CASE_							:				Optional[int]		=HfFileSystem(repo_info=UpperCAmelCase_			,							token=UpperCAmelCase_				)
       assert sorted(hffs.glob('''*'''				)				) == [".gitattributes", "data"]
       assert hffs.isdir('''data'''				)
       assert hffs.isfile('''.gitattributes'''				) and hffs.isfile('''data/text_data.txt'''				)
       with open(UpperCAmelCase_				) as f:
              assert hffs.open('''data/text_data.txt'''			,							'''r'''				).read() == f.read()

def 							SCREAMING_SNAKE_CASE_	(					)			->						Union[str, Any]:
       SCREAMING_SNAKE_CASE_							:				Tuple		='''bz2'''

       # Import module
       import datasets.filesystems

       # Overwrite protocol and reload
       register_implementation(UpperCAmelCase_			,							UpperCAmelCase_			,							clobber=UpperCAmelCase_				)
       with pytest.warns(UpperCAmelCase_				) as warning_info:
              importlib.reload(datasets.filesystems				)

       assert len(UpperCAmelCase_				) == 1
       assert (
           str(warning_info[0].message				)
           == f'A filesystem protocol was already set for {protocol} and will be overwritten.'
       )
