


'''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 	a_					( lowerCamelCase	:     Optional[int]	, lowerCamelCase	:     Optional[Any]=False				):
   try:
      lowerCAmelCase     =			os.environ[key]
   except KeyError:
      # KEY isn't set, default to `default`.
      lowerCAmelCase     =			default
   else:
      # KEY is set, convert it to True or False.
      try:
         lowerCAmelCase     =			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


__snake_case    						=parse_flag_from_env("""RUN_SLOW""", default=False)





def 	a_					( lowerCamelCase	:     Any				):
   return unittest.skip('Test was skipped'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     List[Any]				):
   return unittest.skipUnless(_run_slow_tests	, 'test is slow'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     Dict				):
   return unittest.skipUnless(not torch.cuda.is_available()	, 'test requires only a CPU'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     Any				):
   return unittest.skipUnless(torch.cuda.is_available()	, 'test requires a GPU'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     Union[str, Any]				):
   return unittest.skipUnless(is_xpu_available()	, 'test requires a XPU'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     Optional[Any]				):
   return unittest.skipUnless(is_mps_available()	, 'test requires a `mps` backend support in `torch`'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     Optional[int]				):
   return unittest.skipUnless(
       is_transformers_available() and is_datasets_available()	, 'test requires the Hugging Face suite'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     List[str]				):
   return unittest.skipUnless(is_bnb_available()	, 'test requires the bitsandbytes library'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     Union[str, Any]				):
   return unittest.skipUnless(is_tpu_available()	, 'test requires TPU'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     Union[str, Any]				):
   return unittest.skipUnless(torch.cuda.device_count() == 1	, 'test requires a GPU'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     str				):
   return unittest.skipUnless(torch.xpu.device_count() == 1	, 'test requires a XPU'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     str				):
   return unittest.skipUnless(torch.cuda.device_count() > 1	, 'test requires multiple GPUs'				)(lowerCamelCase				)





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





def 	a_					( lowerCamelCase	:     Tuple				):
   return unittest.skipUnless(is_safetensors_available()	, 'test requires safetensors'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     Optional[int]				):
   return unittest.skipUnless(is_deepspeed_available()	, 'test requires DeepSpeed'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     str				):
   return unittest.skipUnless(is_torch_version('>='	, '1.12.0'				)	, 'test requires torch version >= 1.12.0'				)(lowerCamelCase				)





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





def 	a_					( lowerCamelCase	:     str				):
   return unittest.skipUnless(is_wandb_available()	, 'test requires wandb'				)(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     str				):
   return unittest.skipUnless(is_comet_ml_available()	, 'test requires comet_ml'				)(lowerCamelCase				)


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





def 	a_					( 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 		UpperCAmelCase_      (  unittest.TestCase		):
     lowerCamelCase				:	Union[str, Any]		=     True





     @classmethod
     def 							__UpperCAmelCase      ( cls       :      List[Any]    )				->  Any:
        lowerCAmelCase     =			tempfile.mkdtemp()





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





     def 							__UpperCAmelCase      ( 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(UpperCAmelCase__    )




class 		UpperCAmelCase_      (  unittest.TestCase		):





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  int:
        super().tearDown()
        # Reset the state of the AcceleratorState singleton.
        AcceleratorState._reset_state()
        PartialState._reset_state()




class 		UpperCAmelCase_      (  unittest.TestCase		):





     def 							__UpperCAmelCase      ( self       :      Dict    ,      UpperCAmelCase__       :      Union[mock.Mock, List[mock.Mock]]    )				->  Optional[int]:
        lowerCAmelCase     =			mocks if isinstance(UpperCAmelCase__    ,      (tuple, list)    ) else [mocks]
        for m in self.mocks:
           m.start()
           self.addCleanup(m.stop    )





def 	a_					( lowerCamelCase	:     List[str]				):
   lowerCAmelCase     =			AcceleratorState()
   lowerCAmelCase     =			tensor[None].clone().to(state.device				)
   lowerCAmelCase     =			gather(lowerCamelCase				).cpu()
   lowerCAmelCase     =			tensor[0].cpu()
   for i in range(tensors.shape[0]				):
      if not torch.equal(tensors[i]	, lowerCamelCase				):
         return False
   return True

class 		UpperCAmelCase_      :





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





async def 	a_					( lowerCamelCase	:     Optional[int]	, lowerCamelCase	:     Any				):
   while True:
      lowerCAmelCase     =			await stream.readline()
      if line:
         callback(lowerCamelCase				)
      else:
         break





async def 	a_					( lowerCamelCase	:     Tuple	, lowerCamelCase	:     Optional[int]=None	, lowerCamelCase	:     Optional[int]=None	, lowerCamelCase	:     Optional[Any]=None	, lowerCamelCase	:     Optional[Any]=False	, lowerCamelCase	:     Optional[int]=False				):
   if echo:
      print('\nRunning: '	, ' '.join(lowerCamelCase				)				)

   lowerCAmelCase     =			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)

   lowerCAmelCase     =			[]
   lowerCAmelCase     =			[]

   def tee(lowerCamelCase	:     Optional[int]	, lowerCamelCase	:     int	, lowerCamelCase	:     Union[str, Any]	, lowerCamelCase	:     Tuple=""				):
      lowerCAmelCase     =			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 	a_					( lowerCamelCase	:     List[str]	, lowerCamelCase	:     Union[str, Any]=None	, lowerCamelCase	:     Tuple=None	, lowerCamelCase	:     List[Any]=180	, lowerCamelCase	:     List[Any]=False	, lowerCamelCase	:     Any=True				):
   lowerCAmelCase     =			asyncio.get_event_loop()
   lowerCAmelCase     =			loop.run_until_complete(
       _stream_subprocess(lowerCamelCase	, env=lowerCamelCase	, stdin=lowerCamelCase	, timeout=lowerCamelCase	, quiet=lowerCamelCase	, echo=lowerCamelCase				)				)

   lowerCAmelCase     =			' '.join(lowerCamelCase				)
   if result.returncode > 0:
      lowerCAmelCase     =			'\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 		UpperCAmelCase_      (  __lowercase		):
     pass





def 	a_					( lowerCamelCase	:     List[str]	, lowerCamelCase	:     int=False				):
   try:
      lowerCAmelCase     =			subprocess.check_output(lowerCamelCase	, stderr=subprocess.STDOUT				)
      if return_stdout:
         if hasattr(lowerCamelCase	, 'decode'				):
            lowerCAmelCase     =			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 warnings

from ...utils import logging
from .image_processing_flava import FlavaImageProcessor


__snake_case    						=logging.get_logger(__name__)

class 		UpperCAmelCase_      (  __lowercase		):





     def __init__( self       :      Dict    ,      *UpperCAmelCase__       :      Dict    ,      **UpperCAmelCase__       :      List[str]    )				->  None:
        warnings.warn(
            'The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
            ' use FlavaImageProcessor instead.'    ,      UpperCAmelCase__    ,      )
        super().__init__(*UpperCAmelCase__    ,      **UpperCAmelCase__    )





