

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






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Dict:
	return unittest.skip('Test was skipped'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Optional[Any]:
	return unittest.skipUnless(_run_slow_tests	, 'test is slow'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Any:
	return unittest.skipUnless(not torch.cuda.is_available()	, 'test requires only a CPU'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Optional[int]:
	return unittest.skipUnless(torch.cuda.is_available()	, 'test requires a GPU'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     List[Any]:
	return unittest.skipUnless(is_xpu_available()	, 'test requires a XPU'			)(lowerCamelCase__			)






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






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






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     List[str]:
	return unittest.skipUnless(is_bnb_available()	, 'test requires the bitsandbytes library'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Optional[Any]:
	return unittest.skipUnless(is_tpu_available()	, 'test requires TPU'			)(lowerCamelCase__			)






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






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     str:
	return unittest.skipUnless(torch.xpu.device_count() == 1	, 'test requires a XPU'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Any:
	return unittest.skipUnless(torch.cuda.device_count() > 1	, 'test requires multiple GPUs'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Dict:
	return unittest.skipUnless(torch.xpu.device_count() > 1	, 'test requires multiple XPUs'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Optional[int]:
	return unittest.skipUnless(is_safetensors_available()	, 'test requires safetensors'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     str:
	return unittest.skipUnless(is_deepspeed_available()	, 'test requires DeepSpeed'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Dict:
	return unittest.skipUnless(is_torch_version('>='	, '1.12.0'			)	, 'test requires torch version >= 1.12.0'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__=None	, lowerCamelCase__=None			)  ->     Any:
	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    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Optional[Any]:
	return unittest.skipUnless(is_tensorboard_available()	, 'test requires Tensorboard'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Dict:
	return unittest.skipUnless(is_wandb_available()	, 'test requires wandb'			)(lowerCamelCase__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Dict:
	return unittest.skipUnless(is_comet_ml_available()	, 'test requires comet_ml'			)(lowerCamelCase__			)


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






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     Dict:
	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				):
							_UpperCAmelCase    :  Union[str, Any]						      =      True
							@classmethod
							def     lowerCAmelCase     (		cls		:			int):
								__lowerCamelCase				:				List[Any]					       = tempfile.mkdtemp()
							@classmethod
							def     lowerCAmelCase     (		cls		:			int):
								if os.path.exists(cls.tmpdir):
									shutil.rmtree(cls.tmpdir)


							def     lowerCAmelCase     (		self		:			Any):
								if self.clear_on_setup:
									for path in Path(self.tmpdir).glob('**/*'):
										if path.is_file():
											path.unlink()
										elif path.is_dir():
											shutil.rmtree(SCREAMING_SNAKE_CASE__)






class        A_		(       unittest.TestCase				):
							def     lowerCAmelCase     (		self		:			List[Any]):
								super().tearDown()
								# Reset the state of the AcceleratorState singleton.
								AcceleratorState._reset_state()
								PartialState._reset_state()






class        A_		(       unittest.TestCase				):
							def     lowerCAmelCase     (		self		:			List[str]   ,SCREAMING_SNAKE_CASE__		:			Union[mock.Mock, List[mock.Mock]]):
								__lowerCamelCase				:				Tuple					       = mocks if isinstance(SCREAMING_SNAKE_CASE__   ,(tuple, list)) else [mocks]
								for m in self.mocks:
									m.start()
									self.addCleanup(m.stop)






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






class        A_		:
							def __init__(		self		:			Any   ,SCREAMING_SNAKE_CASE__		:			Optional[int]   ,SCREAMING_SNAKE_CASE__		:			Tuple   ,SCREAMING_SNAKE_CASE__		:			Optional[int]):
								__lowerCamelCase				:				Union[str, Any]					       = returncode
								__lowerCamelCase				:				List[str]					       = stdout
								__lowerCamelCase				:				Tuple					       = stderr






async def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__			)  ->     List[Any]:
	while True:
		__lowerCamelCase				:				str					       = await stream.readline()
		if line:
			callback(lowerCamelCase__			)
		else:
			break






async def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__=None	, lowerCamelCase__=None	, lowerCamelCase__=None	, lowerCamelCase__=False	, lowerCamelCase__=False			)  ->     _RunOutput:
	if echo:
		print('\nRunning: '	, ' '.join(lowerCamelCase__			)			)

	__lowerCamelCase				:				str					       = 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				:				int					       = []
	__lowerCamelCase				:				str					       = []

	def tee(lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__=""			):
		__lowerCamelCase				:				Any					       = 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    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__=None	, lowerCamelCase__=None	, lowerCamelCase__=1_8_0	, lowerCamelCase__=False	, lowerCamelCase__=True			)  ->     _RunOutput:
	__lowerCamelCase				:				Union[str, Any]					       = asyncio.get_event_loop()
	__lowerCamelCase				:				str					       = loop.run_until_complete(
	    _stream_subprocess(lowerCamelCase__	, env=lowerCamelCase__	, stdin=lowerCamelCase__	, timeout=lowerCamelCase__	, quiet=lowerCamelCase__	, echo=lowerCamelCase__			)			)

	__lowerCamelCase				:				Union[str, Any]					       = ' '.join(lowerCamelCase__			)
	if result.returncode > 0:
		__lowerCamelCase				:				Optional[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_		(       SCREAMING_SNAKE_CASE				):
							pass






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__=False			)  ->     int:
	try:
		__lowerCamelCase				:				List[str]					       = subprocess.check_output(lowerCamelCase__	, stderr=subprocess.STDOUT			)
		if return_stdout:
			if hasattr(lowerCamelCase__	, 'decode'			):
				__lowerCamelCase				:				str					       = 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 gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


__A			   = False


class     UpperCAmelCase						(unittest.TestCase  ):



    """simple docstring"""

    pass



@nightly
@require_torch_gpu
class     UpperCAmelCase						(unittest.TestCase  ):



    """simple docstring"""

    def _snake_case			(   self							):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()






    def _snake_case			(   self							):
       lowercase__:   Dict					=      VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion'''							)
       # remove text_unet
       pipe.remove_unused_weights()
       pipe.to(_UpperCAmelCase							)
       pipe.set_progress_bar_config(disable=_UpperCAmelCase							)

       lowercase__:   List[str]					=      '''A painting of a squirrel eating a burger '''
       lowercase__:   str					=      torch.manual_seed(0							)
       lowercase__:   Union[str, Any]					=      pipe(
           prompt=_UpperCAmelCase    ,			generator=_UpperCAmelCase    ,			guidance_scale=7.5    ,			num_inference_steps=2    ,			output_type='''numpy'''							).images

       with tempfile.TemporaryDirectory() as tmpdirname:
          pipe.save_pretrained(_UpperCAmelCase							)
          lowercase__:   Optional[Any]					=      VersatileDiffusionTextToImagePipeline.from_pretrained(_UpperCAmelCase							)
       pipe.to(_UpperCAmelCase							)
       pipe.set_progress_bar_config(disable=_UpperCAmelCase							)

       lowercase__:   Optional[int]					=      generator.manual_seed(0							)
       lowercase__:   List[str]					=      pipe(
           prompt=_UpperCAmelCase    ,			generator=_UpperCAmelCase    ,			guidance_scale=7.5    ,			num_inference_steps=2    ,			output_type='''numpy'''							).images

       assert np.abs(image - new_image							).sum() < 1e-5, "Models don't have the same forward pass"






    def _snake_case			(   self							):
       lowercase__:   Dict					=      VersatileDiffusionTextToImagePipeline.from_pretrained(
           '''shi-labs/versatile-diffusion'''    ,			torch_dtype=torch.floataa							)
       pipe.to(_UpperCAmelCase							)
       pipe.set_progress_bar_config(disable=_UpperCAmelCase							)

       lowercase__:   Tuple					=      '''A painting of a squirrel eating a burger '''
       lowercase__:   Optional[Any]					=      torch.manual_seed(0							)
       lowercase__:   Tuple					=      pipe(
           prompt=_UpperCAmelCase    ,			generator=_UpperCAmelCase    ,			guidance_scale=7.5    ,			num_inference_steps=50    ,			output_type='''numpy'''							).images

       lowercase__:   Union[str, Any]					=      image[0, 253:256, 253:256, -1]

       assert image.shape == (1, 512, 512, 3)
       lowercase__:   Any					=      np.array([0.3_367, 0.3_169, 0.2_656, 0.3_870, 0.4_790, 0.3_796, 0.4_009, 0.4_878, 0.4_778]							)

       assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2
