

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


a					:List[str]    = parse_flag_from_env("RUN_SLOW", default=False)




def  _lowercase					(    __lowerCAmelCase							)       ->				Any:
      return unittest.skip("""Test was skipped"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				str:
      return unittest.skipUnless(_run_slow_tests  ,					"""test is slow"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				Optional[int]:
      return unittest.skipUnless(not torch.cuda.is_available()  ,					"""test requires only a CPU"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				Optional[int]:
      return unittest.skipUnless(torch.cuda.is_available()  ,					"""test requires a GPU"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				List[Any]:
      return unittest.skipUnless(is_xpu_available()  ,					"""test requires a XPU"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				Tuple:
      return unittest.skipUnless(is_mps_available()  ,					"""test requires a `mps` backend support in `torch`"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				Optional[int]:
      return unittest.skipUnless(
          is_transformers_available() and is_datasets_available()  ,					"""test requires the Hugging Face suite"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				Any:
      return unittest.skipUnless(is_bnb_available()  ,					"""test requires the bitsandbytes library"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				int:
      return unittest.skipUnless(is_tpu_available()  ,					"""test requires TPU"""							)(__lowerCAmelCase							)




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




def  _lowercase					(    __lowerCAmelCase							)       ->				int:
      return unittest.skipUnless(torch.xpu.device_count() == 1  ,					"""test requires a XPU"""							)(__lowerCAmelCase							)




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




def  _lowercase					(    __lowerCAmelCase							)       ->				Any:
      return unittest.skipUnless(torch.xpu.device_count() > 1  ,					"""test requires multiple XPUs"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				int:
      return unittest.skipUnless(is_safetensors_available()  ,					"""test requires safetensors"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				Any:
      return unittest.skipUnless(is_deepspeed_available()  ,					"""test requires DeepSpeed"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				Optional[Any]:
      return unittest.skipUnless(is_torch_version(""">="""  ,					"""1.12.0"""							)  ,					"""test requires torch version >= 1.12.0"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase=None  ,					__lowerCAmelCase=None							)       ->				Dict:
      if test_case is None:
            return partial(__lowerCAmelCase  ,					version=__lowerCAmelCase							)
      return unittest.skipUnless(is_torch_version(""">="""  ,					__lowerCAmelCase							)  ,					F'''test requires torch version >= {version}'''							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				Dict:
      return unittest.skipUnless(is_tensorboard_available()  ,					"""test requires Tensorboard"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				List[str]:
      return unittest.skipUnless(is_wandb_available()  ,					"""test requires wandb"""							)(__lowerCAmelCase							)




def  _lowercase					(    __lowerCAmelCase							)       ->				List[Any]:
      return unittest.skipUnless(is_comet_ml_available()  ,					"""test requires comet_ml"""							)(__lowerCAmelCase							)


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




def  _lowercase					(    __lowerCAmelCase							)       ->				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"""  ,					)(__lowerCAmelCase							)

class      __a							(unittest.TestCase):






     '''simple docstring'''
     _SCREAMING_SNAKE_CASE						:Union[str, Any]       = True

     @classmethod
     def 					_a			(						cls  )  ->      List[Any]:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      int      		=	tempfile.mkdtemp()

     @classmethod
     def 					_a			(						cls  )  ->      Optional[int]:


           """simple docstring"""


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





     def 					_a			(						self  )  ->      Dict:


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






     '''simple docstring'''

     def 					_a			(						self  )  ->      Dict:


           """simple docstring"""


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





class      __a							(unittest.TestCase):






     '''simple docstring'''

     def 					_a			(						self	,    _a  )  ->      Optional[Any]:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	mocks if isinstance(_a	,    (tuple, list)  ) else [mocks]
           for m in self.mocks:
                 m.start()
                 self.addCleanup(m.stop  )





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

class      __a							:






     '''simple docstring'''

     def __init__(						self	,    _a	,    _a	,    _a  )  ->      List[str]:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Tuple      		=	returncode
           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	stdout
           SCREAMING_SNAKE_CASE__   :      Tuple      		=	stderr





async def  _lowercase					(    __lowerCAmelCase  ,					__lowerCAmelCase							)       ->				str:
      while True:
            SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	await stream.readline()
            if line:
                  callback(__lowerCAmelCase							)
            else:
                  break




async def  _lowercase					(    __lowerCAmelCase  ,					__lowerCAmelCase=None  ,					__lowerCAmelCase=None  ,					__lowerCAmelCase=None  ,					__lowerCAmelCase=False  ,					__lowerCAmelCase=False							)       ->				_RunOutput:
      if echo:
            print("""\nRunning: """  ,					""" """.join(__lowerCAmelCase							)							)

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

      # 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__   :      Optional[int]      		=	[]
      SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	[]

      def tee(__lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase=""							):
            SCREAMING_SNAKE_CASE__   :      int      		=	line.decode("""utf-8"""							).rstrip()
            sink.append(__lowerCAmelCase							)
            if not quiet:
                  print(__lowerCAmelCase  ,					__lowerCAmelCase  ,					file=__lowerCAmelCase							)

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




def  _lowercase					(    __lowerCAmelCase  ,					__lowerCAmelCase=None  ,					__lowerCAmelCase=None  ,					__lowerCAmelCase=180  ,					__lowerCAmelCase=False  ,					__lowerCAmelCase=True							)       ->				_RunOutput:
      SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	asyncio.get_event_loop()
      SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	loop.run_until_complete(
          _stream_subprocess(__lowerCAmelCase  ,					env=__lowerCAmelCase  ,					stdin=__lowerCAmelCase  ,					timeout=__lowerCAmelCase  ,					quiet=__lowerCAmelCase  ,					echo=__lowerCAmelCase							)							)

      SCREAMING_SNAKE_CASE__   :      Any      		=	""" """.join(__lowerCAmelCase							)
      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      __a							(UpperCamelCase_):






     '''simple docstring'''
     pass





def  _lowercase					(    __lowerCAmelCase  ,					__lowerCAmelCase=False							)       ->				str:
      try:
            SCREAMING_SNAKE_CASE__   :      Any      		=	subprocess.check_output(__lowerCAmelCase  ,					stderr=subprocess.STDOUT							)
            if return_stdout:
                  if hasattr(__lowerCAmelCase  ,					"""decode"""							):
                        SCREAMING_SNAKE_CASE__   :      Tuple      		=	output.decode("""utf-8"""							)
                  return output
      except subprocess.CalledProcessError as e:
            raise SubprocessCallException(
                F'''Command `{' '.join(__lowerCAmelCase							)}` failed with the following error:\n\n{e.output.decode()}'''							) from e







"""simple docstring"""


import re
from pathlib import Path
from unittest import TestCase

import pytest

@pytest.mark.integration
class      __a							(UpperCamelCase_):






     '''simple docstring'''

     def 					_a			(						self	,    _a  )  ->      Union[str, Any]:


           """simple docstring"""


           with open(_a	,    encoding="""utf-8"""  ) as input_file:
                 SCREAMING_SNAKE_CASE__   :      str      		=	re.compile(r"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)"""  )
                 SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	input_file.read()
                 SCREAMING_SNAKE_CASE__   :      str      		=	regexp.search(_a  )

           return match

     def 					_a			(						self	,    _a  )  ->      Optional[Any]:


           """simple docstring"""


           with open(_a	,    encoding="""utf-8"""  ) as input_file:
                 SCREAMING_SNAKE_CASE__   :      Tuple      		=	re.compile(r"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()"""	,    re.DOTALL  )
                 SCREAMING_SNAKE_CASE__   :      List[Any]      		=	input_file.read()
                 # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search`
                 SCREAMING_SNAKE_CASE__   :      Dict      		=	regexp.finditer(_a  )

           SCREAMING_SNAKE_CASE__   :      int      		=	[match for match in matches if match is not None and match.group(1  ) is not None]
           return matches[0] if matches else None

     def 					_a			(						self  )  ->      str:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	Path("""./datasets"""  )
           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	list(dataset_paths.absolute().glob("""**/*.py"""  )  )

           for dataset in dataset_files:
                 if self._no_encoding_on_file_open(str(_a  )  ):
                       raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}'''  )





     def 					_a			(						self  )  ->      Dict:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	Path("""./datasets"""  )
           SCREAMING_SNAKE_CASE__   :      List[str]      		=	list(dataset_paths.absolute().glob("""**/*.py"""  )  )

           for dataset in dataset_files:
                 if self._no_print_statements(str(_a  )  ):
                       raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.'''  )




