





'''simple docstring'''






import os
from typing import Any, Callable, Dict, List, Optional, Tuple, Union

import torch
from torch import nn

from ...models.controlnet import ControlNetModel, ControlNetOutput
from ...models.modeling_utils import ModelMixin
from ...utils import logging


__lowerCamelCase						: Any		=   logging.get_logger(__name__)







class 		UpperCAmelCase   (				lowercase_):


		"""simple docstring"""







		def __init__(				self    :					Dict							,	UpperCamelCase__    :					Union[List[ControlNetModel], Tuple[ControlNetModel]]  )     ->						List[str]:
				super().__init__()
				_UpperCamelCase       			=nn.ModuleList(UpperCamelCase__  )


		def   UpperCamelCase__      (				self    :					List[Any]							,	UpperCamelCase__    :					torch.FloatTensor							,	UpperCamelCase__    :					Union[torch.Tensor, float, int]							,	UpperCamelCase__    :					torch.Tensor							,	UpperCamelCase__    :					List[torch.tensor]							,	UpperCamelCase__    :					List[float]							,	UpperCamelCase__    :					Optional[torch.Tensor] = None							,	UpperCamelCase__    :					Optional[torch.Tensor] = None							,	UpperCamelCase__    :					Optional[torch.Tensor] = None							,	UpperCamelCase__    :					Optional[Dict[str, Any]] = None							,	UpperCamelCase__    :					bool = False							,	UpperCamelCase__    :					bool = True							,	)     ->						Union[ControlNetOutput, Tuple]:
				for i, (image, scale, controlnet) in enumerate(zip(UpperCamelCase__							,	UpperCamelCase__							,	self.nets  )  ):
						_UpperCamelCase			,     _UpperCamelCase       			=controlnet(
						    UpperCamelCase__							,	UpperCamelCase__							,	UpperCamelCase__							,	UpperCamelCase__							,	UpperCamelCase__							,	UpperCamelCase__							,	UpperCamelCase__							,	UpperCamelCase__							,	UpperCamelCase__							,	UpperCamelCase__							,	UpperCamelCase__							,	)

						# merge samples
						if i == 0:
								_UpperCamelCase			,     _UpperCamelCase       			=down_samples, mid_sample
						else:
								_UpperCamelCase       			=[
								    samples_prev + samples_curr
								    for samples_prev, samples_curr in zip(UpperCamelCase__							,	UpperCamelCase__  )
								]
								mid_block_res_sample += mid_sample

				return down_block_res_samples, mid_block_res_sample


		def   UpperCamelCase__      (				self    :					int							,	UpperCamelCase__    :					Union[str, os.PathLike]							,	UpperCamelCase__    :					bool = True							,	UpperCamelCase__    :					Callable = None							,	UpperCamelCase__    :					bool = False							,	UpperCamelCase__    :					Optional[str] = None							,	)     ->						Union[str, Any]:
				_UpperCamelCase       			=0
				_UpperCamelCase       			=save_directory
				for controlnet in self.nets:
						controlnet.save_pretrained(
						    UpperCamelCase__							,	is_main_process=UpperCamelCase__							,	save_function=UpperCamelCase__							,	safe_serialization=UpperCamelCase__							,	variant=UpperCamelCase__							,	)

						idx += 1
						_UpperCamelCase       			=model_path_to_save + F'''_{idx}'''




		@classmethod
		def   UpperCamelCase__      (				cls    :					List[str]							,	UpperCamelCase__    :					Optional[Union[str, os.PathLike]]							,	**UpperCamelCase__    :					Any  )     ->						List[Any]:
				_UpperCamelCase       			=0
				_UpperCamelCase       			=[]

				# load controlnet and append to list until no controlnet directory exists anymore
				# first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained`
				# second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ...
				_UpperCamelCase       			=pretrained_model_path
				while os.path.isdir(UpperCamelCase__  ):
						_UpperCamelCase       			=ControlNetModel.from_pretrained(UpperCamelCase__							,	**UpperCamelCase__  )
						controlnets.append(UpperCamelCase__  )

						idx += 1
						_UpperCamelCase       			=pretrained_model_path + F'''_{idx}'''

				logger.info(F'''{len(UpperCamelCase__  )} controlnets loaded from {pretrained_model_path}.'''  )

				if len(UpperCamelCase__  ) == 0:
						raise ValueError(
						    F'''No ControlNets found under {os.path.dirname(UpperCamelCase__  )}. Expected at least {pretrained_model_path + '_0'}.'''  )

				return cls(UpperCamelCase__  )













'''simple docstring'''






import importlib.util
import os
import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import (
    is_accelerate_available,
    is_flax_available,
    is_safetensors_available,
    is_tf_available,
    is_torch_available,
)
from . import BaseTransformersCLICommand


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  return EnvironmentCommand()


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  return EnvironmentCommand(args.accelerate_config_file   )







class 		UpperCAmelCase   (				lowercase_):


  """simple docstring"""







  @staticmethod
  def   UpperCamelCase__      (				UpperCamelCase__    :					ArgumentParser  )     ->						Union[str, Any]:
    _UpperCamelCase       			=parser.add_parser('''env'''  )
    download_parser.set_defaults(func=UpperCamelCase__  )
    download_parser.add_argument(
        '''--accelerate-config_file'''							,	default=UpperCamelCase__							,	help='''The accelerate config file to use for the default values in the launching script.'''							,	)
    download_parser.set_defaults(func=UpperCamelCase__  )


  def __init__(				self    :					Tuple							,	UpperCamelCase__    :					Dict							,	*UpperCamelCase__    :					str  )     ->						None:
    _UpperCamelCase       			=accelerate_config_file


  def   UpperCamelCase__      (				self    :					str  )     ->						int:
    _UpperCamelCase       			='''not installed'''
    if is_safetensors_available():
      import safetensors

      _UpperCamelCase       			=safetensors.__version__
    elif importlib.util.find_spec('''safetensors'''  ) is not None:
      import safetensors

      _UpperCamelCase       			=F'''{safetensors.__version__} but is ignored because of PyTorch version too old.'''

    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			=_UpperCamelCase       			='''not found'''
    if is_accelerate_available():
      import accelerate
      from accelerate.commands.config import default_config_file, load_config_from_file

      _UpperCamelCase       			=accelerate.__version__
      # Get the default from the config file.
      if self._accelerate_config_file is not None or os.path.isfile(UpperCamelCase__  ):
        _UpperCamelCase       			=load_config_from_file(self._accelerate_config_file  ).to_dict()

      _UpperCamelCase       			=(
          '''\n'''.join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]  )
          if isinstance(UpperCamelCase__							,	UpperCamelCase__  )
          else F'''\t{accelerate_config}'''
      )

    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			='''NA'''
    if is_torch_available():
      import torch

      _UpperCamelCase       			=torch.__version__
      _UpperCamelCase       			=torch.cuda.is_available()

    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			='''NA'''
    if is_tf_available():
      import tensorflow as tf

      _UpperCamelCase       			=tf.__version__
      try:
        # deprecated in v2.1
        _UpperCamelCase       			=tf.test.is_gpu_available()
      except AttributeError:
        # returns list of devices, convert to bool
        _UpperCamelCase       			=bool(tf.config.list_physical_devices('''GPU'''  )  )

    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			='''NA'''
    if is_flax_available():
      import flax
      import jax
      import jaxlib

      _UpperCamelCase       			=flax.__version__
      _UpperCamelCase       			=jax.__version__
      _UpperCamelCase       			=jaxlib.__version__
      _UpperCamelCase       			=jax.lib.xla_bridge.get_backend().platform

    _UpperCamelCase       			={
        '''`transformers` version''': version,
        '''Platform''': platform.platform(),
        '''Python version''': platform.python_version(),
        '''Huggingface_hub version''': huggingface_hub.__version__,
        '''Safetensors version''': F'''{safetensors_version}''',
        '''Accelerate version''': F'''{accelerate_version}''',
        '''Accelerate config''': F'''{accelerate_config_str}''',
        '''PyTorch version (GPU?)''': F'''{pt_version} ({pt_cuda_available})''',
        '''Tensorflow version (GPU?)''': F'''{tf_version} ({tf_cuda_available})''',
        '''Flax version (CPU?/GPU?/TPU?)''': F'''{flax_version} ({jax_backend})''',
        '''Jax version''': F'''{jax_version}''',
        '''JaxLib version''': F'''{jaxlib_version}''',
        '''Using GPU in script?''': '''<fill in>''',
        '''Using distributed or parallel set-up in script?''': '''<fill in>''',
    }

    print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n'''  )
    print(self.format_dict(UpperCamelCase__  )  )

    return info




  @staticmethod
  def   UpperCamelCase__      (				UpperCamelCase__    :					Optional[Any]  )     ->						Dict:
    return "\n".join([F'''- {prop}: {val}''' for prop, val in d.items()]  ) + "\n"






