


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


lowerCAmelCase   : Optional[Any]             =				parse_flag_from_env("""RUN_SLOW""", default=False)




def 	_A  (       A							)  ->				int:
	return unittest.skip("Test was skipped"							)(A							)




def 	_A  (       A							)  ->				Optional[Any]:
	return unittest.skipUnless(_run_slow_tests							,"test is slow"							)(A							)




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




def 	_A  (       A							)  ->				List[str]:
	return unittest.skipUnless(torch.cuda.is_available()							,"test requires a GPU"							)(A							)




def 	_A  (       A							)  ->				Union[str, Any]:
	return unittest.skipUnless(is_xpu_available()							,"test requires a XPU"							)(A							)




def 	_A  (       A							)  ->				Any:
	return unittest.skipUnless(is_mps_available()							,"test requires a `mps` backend support in `torch`"							)(A							)




def 	_A  (       A							)  ->				Any:
	return unittest.skipUnless(
	    is_transformers_available() and is_datasets_available()							,"test requires the Hugging Face suite"							)(A							)




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




def 	_A  (       A							)  ->				str:
	return unittest.skipUnless(is_tpu_available()							,"test requires TPU"							)(A							)




def 	_A  (       A							)  ->				Tuple:
	return unittest.skipUnless(torch.cuda.device_count() == 1							,"test requires a GPU"							)(A							)




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




def 	_A  (       A							)  ->				Any:
	return unittest.skipUnless(torch.cuda.device_count() > 1							,"test requires multiple GPUs"							)(A							)




def 	_A  (       A							)  ->				Dict:
	return unittest.skipUnless(torch.xpu.device_count() > 1							,"test requires multiple XPUs"							)(A							)




def 	_A  (       A							)  ->				Any:
	return unittest.skipUnless(is_safetensors_available()							,"test requires safetensors"							)(A							)




def 	_A  (       A							)  ->				int:
	return unittest.skipUnless(is_deepspeed_available()							,"test requires DeepSpeed"							)(A							)




def 	_A  (       A							)  ->				str:
	return unittest.skipUnless(is_torch_version(">="							,"1.12.0"							)							,"test requires torch version >= 1.12.0"							)(A							)




def 	_A  (       A=None							,A=None							)  ->				List[Any]:
	if test_case is None:
		return partial(A							,version=A							)
	return unittest.skipUnless(is_torch_version(">="							,A							)							,F'''test requires torch version >= {version}'''							)(A							)




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




def 	_A  (       A							)  ->				str:
	return unittest.skipUnless(is_wandb_available()							,"test requires wandb"							)(A							)




def 	_A  (       A							)  ->				Dict:
	return unittest.skipUnless(is_comet_ml_available()							,"test requires comet_ml"							)(A							)


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




def 	_A  (       A							)  ->				int:
	return unittest.skipUnless(
	    _atleast_one_tracker_available							,"test requires at least one tracker to be available and for `comet_ml` to not be installed"							,)(A							)




class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


				_snake_case						       =				True

				@classmethod
				def 	a__		(     cls							)    ->  int:
					lowercase						:		int   					=		tempfile.mkdtemp()

				@classmethod
				def 	a__		(     cls							)    ->  Optional[Any]:
					if os.path.exists(cls.tmpdir							):
						shutil.rmtree(cls.tmpdir							)


				def 	a__		(     self							)    ->  List[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(a_							)




class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


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




class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


				def 	a__		(     self							,      a_							)    ->  Any:
					lowercase						:		Optional[int]   					=		mocks if isinstance(a_							,      (tuple, list)							) else [mocks]
					for m in self.mocks:
						m.start()
						self.addCleanup(m.stop							)




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




class        _UpperCamelCase	:


				'''simple docstring'''


				def __init__(     self							,      a_							,      a_							,      a_							)    ->  str:
					lowercase						:		str   					=		returncode
					lowercase						:		Optional[Any]   					=		stdout
					lowercase						:		Optional[int]   					=		stderr




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




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

	lowercase						:		Tuple   					=		await asyncio.create_subprocess_exec(
	    cmd[0]							,*cmd[1:]							,stdin=A							,stdout=asyncio.subprocess.PIPE							,stderr=asyncio.subprocess.PIPE							,env=A							,)

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

	def tee(A							,A							,A							,A=""							):
		lowercase						:		Tuple   					=		line.decode("utf-8"							).rstrip()
		sink.append(A							)
		if not quiet:
			print(A							,A							,file=A							)

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




def 	_A  (       A							,A=None							,A=None							,A=1_8_0							,A=False							,A=True							)  ->				_RunOutput:
	lowercase						:		List[Any]   					=		asyncio.get_event_loop()
	lowercase						:		int   					=		loop.run_until_complete(
	    _stream_subprocess(A							,env=A							,stdin=A							,timeout=A							,quiet=A							,echo=A							)							)

	lowercase						:		Tuple   					=		" ".join(A							)
	if result.returncode > 0:
		lowercase						:		Union[str, 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        _UpperCamelCase	(    SCREAMING_SNAKE_CASE):


				'''simple docstring'''


				pass




def 	_A  (       A							,A=False							)  ->				Optional[Any]:
	try:
		lowercase						:		Dict   					=		subprocess.check_output(A							,stderr=subprocess.STDOUT							)
		if return_stdout:
			if hasattr(A							,"decode"							):
				lowercase						:		Any   					=		output.decode("utf-8"							)
			return output
	except subprocess.CalledProcessError as e:
		raise SubprocessCallException(
		    F'''Command `{' '.join(A							)}` failed with the following error:\n\n{e.output.decode()}'''							) from e






'''simple docstring'''
from ...utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_torch_available,
    is_transformers_available,
)


try:
					if not (is_transformers_available() and is_torch_available()):
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					from ...utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
					from .multicontrolnet import MultiControlNetModel
					from .pipeline_controlnet import StableDiffusionControlNetPipeline
					from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline
					from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline


if is_transformers_available() and is_flax_available():
					from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline


