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


SCREAMING_SNAKE_CASE_:     Any  =logging.get_logger(__name__)




class        __A      ( UpperCamelCase__	):



    def __init__(self    :    Tuple   ,			__a    :    Union[List[ControlNetModel], Tuple[ControlNetModel]] ):
         super().__init__()
         UpperCAmelCase_           =   nn.ModuleList(__a )



    def 					_lowercase						(self    :    Tuple   ,			__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   ,			):
         for i, (image, scale, controlnet) in enumerate(zip(__a   ,			__a   ,			self.nets ) ):
              UpperCAmelCase_    , UpperCAmelCase_           =   controlnet(
                  __a   ,			__a   ,			__a   ,			__a   ,			__a   ,			__a   ,			__a   ,			__a   ,			__a   ,			__a   ,			__a   ,			)

              # merge samples
              if i == 0:
                   UpperCAmelCase_    , UpperCAmelCase_           =   down_samples, mid_sample
              else:
                   UpperCAmelCase_           =   [
                       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 					_lowercase						(self    :    List[str]   ,			__a    :    Union[str, os.PathLike]   ,			__a    :    bool = True   ,			__a    :    Callable = None   ,			__a    :    bool = False   ,			__a    :    Optional[str] = None   ,			):
         UpperCAmelCase_           =   0
         UpperCAmelCase_           =   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
              UpperCAmelCase_           =   model_path_to_save + f"""_{idx}"""






    @classmethod
    def 					_lowercase						(cls    :    Tuple   ,			__a    :    Optional[Union[str, os.PathLike]]   ,			**__a    :    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(__a ):
              UpperCAmelCase_           =   ControlNetModel.from_pretrained(__a   ,			**__a )
              controlnets.append(__a )

              idx += 1
              UpperCAmelCase_           =   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_						)





