


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


_A		       =						logging.get_logger(__name__)






class     UpperCAmelCase__       (					A_		):



    """simple docstring"""






    def __init__(			self					,   A_    )  ->       Optional[int]:
         super().__init__()
         __UpperCamelCase    							=nn.ModuleList(A_    )






    def _a					(			self					,   A_					,   A_					,   A_					,   A_					,   A_					,   A_ = None					,   A_ = None					,   A_ = None					,   A_ = None					,   A_ = False					,   A_ = True					,   )  ->       Union[ControlNetOutput, Tuple]:
         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 _a					(			self					,   A_					,   A_ = True					,   A_ = None					,   A_ = False					,   A_ = None					,   )  ->       Optional[Any]:
         __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 _a					(			cls					,   A_					,   **A_    )  ->       List[str]:
         __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_    )









# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


_A		       =						{
    'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'],
}
try:
   if not is_vision_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _A		       =						['VivitImageProcessor']


try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _A		       =						[
       'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST',
       'VivitModel',
       'VivitPreTrainedModel',
       'VivitForVideoClassification',
   ]


if TYPE_CHECKING:
   from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig

   try:
      if not is_vision_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .image_processing_vivit import VivitImageProcessor

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_vivit import (
          VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
          VivitForVideoClassification,
          VivitModel,
          VivitPreTrainedModel,
      )


else:
   import sys

   _A		       =						_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)





