


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


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






def      a__ (				__lowercase   )	->	List[str]:
				return unittest.skip("Test was skipped"   )(__lowercase   )






def      a__ (				__lowercase   )	->	Dict:
				return unittest.skipUnless(_run_slow_tests     ,			"test is slow"   )(__lowercase   )






def      a__ (				__lowercase   )	->	Union[str, Any]:
				return unittest.skipUnless(not torch.cuda.is_available()     ,			"test requires only a CPU"   )(__lowercase   )






def      a__ (				__lowercase   )	->	List[Any]:
				return unittest.skipUnless(torch.cuda.is_available()     ,			"test requires a GPU"   )(__lowercase   )






def      a__ (				__lowercase   )	->	Tuple:
				return unittest.skipUnless(is_xpu_available()     ,			"test requires a XPU"   )(__lowercase   )






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






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






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






def      a__ (				__lowercase   )	->	Optional[Any]:
				return unittest.skipUnless(is_tpu_available()     ,			"test requires TPU"   )(__lowercase   )






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






def      a__ (				__lowercase   )	->	List[Any]:
				return unittest.skipUnless(torch.xpu.device_count() == 1     ,			"test requires a XPU"   )(__lowercase   )






def      a__ (				__lowercase   )	->	Union[str, Any]:
				return unittest.skipUnless(torch.cuda.device_count() > 1     ,			"test requires multiple GPUs"   )(__lowercase   )






def      a__ (				__lowercase   )	->	Optional[Any]:
				return unittest.skipUnless(torch.xpu.device_count() > 1     ,			"test requires multiple XPUs"   )(__lowercase   )






def      a__ (				__lowercase   )	->	Optional[int]:
				return unittest.skipUnless(is_safetensors_available()     ,			"test requires safetensors"   )(__lowercase   )






def      a__ (				__lowercase   )	->	str:
				return unittest.skipUnless(is_deepspeed_available()     ,			"test requires DeepSpeed"   )(__lowercase   )






def      a__ (				__lowercase   )	->	Any:
				return unittest.skipUnless(is_torch_version(">="     ,			"1.12.0"   )     ,			"test requires torch version >= 1.12.0"   )(__lowercase   )






def      a__ (				__lowercase=None     ,			__lowercase=None   )	->	List[Any]:
				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      a__ (				__lowercase   )	->	int:
				return unittest.skipUnless(is_tensorboard_available()     ,			"test requires Tensorboard"   )(__lowercase   )






def      a__ (				__lowercase   )	->	Tuple:
				return unittest.skipUnless(is_wandb_available()     ,			"test requires wandb"   )(__lowercase   )






def      a__ (				__lowercase   )	->	Tuple:
				return unittest.skipUnless(is_comet_ml_available()     ,			"test requires comet_ml"   )(__lowercase   )


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






def      a__ (				__lowercase   )	->	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"     ,			)(__lowercase   )
class snake_case      (  unittest.TestCase):
		__UpperCamelCase           =			True







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





						'''simple docstring'''







						_A					  =			tempfile.mkdtemp()







		@classmethod
		def  a_ (					cls      :       Dict		)       ->						List[str]:





						'''simple docstring'''







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







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





						'''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 snake_case      (  unittest.TestCase):







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





						'''simple docstring'''







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





class snake_case      (  unittest.TestCase):







		def  a_ (					self      :       str    ,   a__      :       Union[mock.Mock, List[mock.Mock]]		)       ->						List[str]:





						'''simple docstring'''







						_A					  =			mocks if isinstance(a__    ,   (tuple, list)		) else [mocks]
						for m in self.mocks:
										m.start()
										self.addCleanup(m.stop		)






def      a__ (				__lowercase   )	->	str:
				_A					  =			AcceleratorState()
				_A					  =			tensor[None].clone().to(state.device   )
				_A					  =			gather(__lowercase   ).cpu()
				_A					  =			tensor[0].cpu()
				for i in range(tensors.shape[0]   ):
								if not torch.equal(tensors[i]     ,			__lowercase   ):
												return False
				return True
class snake_case      :







		def __init__(					self      :       int    ,   a__      :       Optional[Any]    ,   a__      :       List[str]    ,   a__      :       Optional[int]		)       ->						Union[str, Any]:





						'''simple docstring'''







						_A					  =			returncode
						_A					  =			stdout
						_A					  =			stderr






async def      a__ (				__lowercase     ,			__lowercase   )	->	Union[str, Any]:
				while True:
								_A					  =			await stream.readline()
								if line:
												callback(__lowercase   )
								else:
												break






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

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

				_A					  =			[]
				_A					  =			[]

				def tee(__lowercase     ,			__lowercase     ,			__lowercase     ,			__lowercase=""   ):
								_A					  =			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      a__ (				__lowercase     ,			__lowercase=None     ,			__lowercase=None     ,			__lowercase=180     ,			__lowercase=False     ,			__lowercase=True   )	->	_RunOutput:
				_A					  =			asyncio.get_event_loop()
				_A					  =			loop.run_until_complete(
				    _stream_subprocess(__lowercase     ,			env=__lowercase     ,			stdin=__lowercase     ,			timeout=__lowercase     ,			quiet=__lowercase     ,			echo=__lowercase   )   )

				_A					  =			" ".join(__lowercase   )
				if result.returncode > 0:
								_A					  =			"\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 snake_case      (  _UpperCamelCase):
		pass






def      a__ (				__lowercase     ,			__lowercase=False   )	->	Tuple:
				try:
								_A					  =			subprocess.check_output(__lowercase     ,			stderr=subprocess.STDOUT   )
								if return_stdout:
												if hasattr(__lowercase     ,			"decode"   ):
																_A					  =			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



"""simple docstring"""


import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


a_       							=    False
class snake_case      (  unittest.TestCase):
		pass





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







		def  a_ (					self      :       Optional[int]		)       ->						str:





						'''simple docstring'''







						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()







		def  a_ (					self      :       Tuple		)       ->						Any:





						'''simple docstring'''







						_A					  =			VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion"    ,   torch_dtype=torch.floataa		)
						pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)

						_A					  =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"		)

						_A					  =			torch.manual_seed(0		)
						_A					  =			pipe.dual_guided(
						    prompt="first prompt"    ,   image=a__    ,   text_to_image_strength=0.7_5    ,   generator=a__    ,   guidance_scale=7.5    ,   num_inference_steps=2    ,   output_type="numpy"    ,   ).images

						with tempfile.TemporaryDirectory() as tmpdirname:
										pipe.save_pretrained(a__		)
										_A					  =			VersatileDiffusionPipeline.from_pretrained(a__    ,   torch_dtype=torch.floataa		)
						pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)

						_A					  =			generator.manual_seed(0		)
						_A					  =			pipe.dual_guided(
						    prompt="first prompt"    ,   image=a__    ,   text_to_image_strength=0.7_5    ,   generator=a__    ,   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  a_ (					self      :       Optional[int]		)       ->						List[Any]:





						'''simple docstring'''







						_A					  =			VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion"    ,   torch_dtype=torch.floataa		)
						pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)

						_A					  =			"cyberpunk 2077"
						_A					  =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"		)
						_A					  =			torch.manual_seed(0		)
						_A					  =			pipe.dual_guided(
						    prompt=a__    ,   image=a__    ,   text_to_image_strength=0.7_5    ,   generator=a__    ,   guidance_scale=7.5    ,   num_inference_steps=50    ,   output_type="numpy"    ,   ).images

						_A					  =			image[0, 2_53:2_56, 2_53:2_56, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						_A					  =			np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1]		)

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

						_A					  =			"A painting of a squirrel eating a burger "
						_A					  =			torch.manual_seed(0		)
						_A					  =			pipe.text_to_image(
						    prompt=a__    ,   generator=a__    ,   guidance_scale=7.5    ,   num_inference_steps=50    ,   output_type="numpy"		).images

						_A					  =			image[0, 2_53:2_56, 2_53:2_56, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						_A					  =			np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8]		)

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

						_A					  =			pipe.image_variation(a__    ,   generator=a__    ,   output_type="numpy"		).images

						_A					  =			image[0, 2_53:2_56, 2_53:2_56, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						_A					  =			np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6]		)

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