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		:		str  ,    a		:		Union[List[ControlNetModel], Tuple[ControlNetModel]]   ):





         """simple docstring"""



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






     def        SCREAMING_SNAKE_CASE__       (			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  ,    ):





         """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		:		List[str]  ,    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		:		Union[str, Any]  ,    a		:		Optional[Union[str, os.PathLike]]  ,    **a		:		Optional[int]   ):





         """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   )

'''simple docstring'''




def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    )     ->   float:
    if principal <= 0:
        raise Exception('''Principal borrowed must be > 0'''    )
    if rate_per_annum < 0:
        raise Exception('''Rate of interest must be >= 0'''    )
    if years_to_repay <= 0 or not isinstance(UpperCamelCase__    ,  UpperCamelCase__    ):
        raise Exception('''Years to repay must be an integer > 0'''    )

    # Yearly rate is divided by 12 to get monthly rate
    __lowerCamelCase          =  rate_per_annum / 12

    # Years to repay is multiplied by 12 to get number of payments as payment is monthly
    __lowerCamelCase          =  years_to_repay * 12

    return (
        principal
        * rate_per_month
        * (1 + rate_per_month) ** number_of_payments
        / ((1 + rate_per_month) ** number_of_payments - 1)
    )


if __name__ == "__main__":
  import doctest

  doctest.testmod()
