'''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


__UpperCAmelCase     							=logging.get_logger(__name__)




class     a__      (   UpperCAmelCase__ ):






     def __init__( self		:		Optional[Any]  ,				a		:		Union[List[ControlNetModel], Tuple[ControlNetModel]]    ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase		=  nn.ModuleList(a    )






     def    SCREAMING_SNAKE_CASE__   ( self		:		Any  ,				a		:		torch.FloatTensor  ,				a		:		Union[torch.Tensor, float, int]  ,				a		:		torch.Tensor  ,				a		:		List[torch.tensor]  ,				a		:		List[float]  ,				a		:		Optional[torch.Tensor] = None  ,				a		:		Optional[torch.Tensor] = None  ,				a		:		Optional[torch.Tensor] = None  ,				a		:		Optional[Dict[str, Any]] = None  ,				a		:		bool = False  ,				a		:		bool = True  ,				):





         """simple docstring"""



         for i, (image, scale, controlnet) in enumerate(zip(a  ,				a  ,				self.nets    )    ):
             __lowerCamelCase	,  __lowerCamelCase		=  controlnet(
                 a  ,				a  ,				a  ,				a  ,				a  ,				a  ,				a  ,				a  ,				a  ,				a  ,				a  ,				)

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

         return down_block_res_samples, mid_block_res_sample






     def    SCREAMING_SNAKE_CASE__   ( self		:		Any  ,				a		:		Union[str, os.PathLike]  ,				a		:		bool = True  ,				a		:		Callable = None  ,				a		:		bool = False  ,				a		:		Optional[str] = None  ,				):





         """simple docstring"""



         __lowerCamelCase		=  0
         __lowerCamelCase		=  save_directory
         for controlnet in self.nets:
             controlnet.save_pretrained(
                 a  ,				is_main_process=a  ,				save_function=a  ,				safe_serialization=a  ,				variant=a  ,				)

             idx += 1
             __lowerCamelCase		=  model_path_to_save + f"""_{idx}"""






     @classmethod
     def    SCREAMING_SNAKE_CASE__   ( cls		:		List[str]  ,				a		:		Optional[Union[str, os.PathLike]]  ,				**a		:		Optional[Any]    ):





         """simple docstring"""



         __lowerCamelCase		=  0
         __lowerCamelCase		=  []

         # 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`, ...
         __lowerCamelCase		=  pretrained_model_path
         while os.path.isdir(a    ):
             __lowerCamelCase		=  ControlNetModel.from_pretrained(a  ,				**a    )
             controlnets.append(a    )

             idx += 1
             __lowerCamelCase		=  pretrained_model_path + f"""_{idx}"""

         logger.info(f"""{len(a    )} controlnets loaded from {pretrained_model_path}."""    )

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

         return cls(a    )




import sys

from .dependency_versions_table import deps
from .utils.versions import require_version, require_version_core


# define which module versions we always want to check at run time
# (usually the ones defined in `install_requires` in setup.py)
#
# order specific notes:
# - tqdm must be checked before tokenizers

snake_case				:    Union[str, Any]       				=     '''python tqdm regex requests packaging filelock numpy tokenizers'''.split()
if sys.version_info < (3, 7):
     pkgs_to_check_at_runtime.append('''dataclasses''')
if sys.version_info < (3, 8):
     pkgs_to_check_at_runtime.append('''importlib_metadata''')

for pkg in pkgs_to_check_at_runtime:
     if pkg in deps:
          if pkg == "tokenizers":
               # must be loaded here, or else tqdm check may fail
               from .utils import is_tokenizers_available

               if not is_tokenizers_available():
                    continue  # not required, check version only if installed

          require_version_core(deps[pkg])
     else:
          raise ValueError(F"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""")
def 				__lowerCamelCase						( UpperCAmelCase_						:		Any ,  UpperCAmelCase_						:		Optional[int]=None						):




      """simple docstring"""





      require_version(deps[pkg] ,  UpperCAmelCase_						)





