
'''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         =    logging.get_logger(__name__)







class UpperCAmelCase__	( lowercase__	):





  """simple docstring"""

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


     '''simple docstring'''






     super().__init__()
     _a				:	Union[str, Any]			=   nn.ModuleList(_a       )


  def   __lowercase		(		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       )       ):
        _a,  _a				:	int			=   controlnet(
            _a							,_a							,_a							,_a							,_a							,_a							,_a							,_a							,_a							,_a							,_a							,)

        # merge samples
        if i == 0:
           _a,  _a				:	List[str]			=   down_samples, mid_sample
        else:
           _a				:	str			=   [
               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      :     int							,_a      :     Union[str, os.PathLike]							,_a      :     bool = True							,_a      :     Callable = None							,_a      :     bool = False							,_a      :     Optional[str] = None							,):


     '''simple docstring'''






     _a				:	Dict			=   0
     _a				:	int			=   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
        _a				:	Optional[Any]			=   model_path_to_save + F"""_{idx}"""


  @classmethod
  def   __lowercase		(		cls      :     str							,_a      :     Optional[Union[str, os.PathLike]]							,**_a      :     List[str]       ):


     '''simple docstring'''






     _a				:	Union[str, Any]			=   0
     _a				:	str			=   []

     # 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`, ...
     _a				:	Optional[Any]			=   pretrained_model_path
     while os.path.isdir(_a       ):
        _a				:	str			=   ControlNetModel.from_pretrained(_a							,**_a       )
        controlnets.append(_a       )

        idx += 1
        _a				:	Optional[int]			=   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'''







import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


__lowerCAmelCase         =    logging.getLogger()







@unittest.skip('''Temporarily disable the doc tests.'''	)
@require_torch
@require_tf
@slow
class UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  def   __lowercase		(		self      :     str							,_a      :     Path							,_a      :     Union[str, None] = None							,_a      :     Union[List[str], None] = None							,_a      :     Union[str, List[str], None] = None							,_a      :     bool = True							,):


     '''simple docstring'''






     _a				:	Optional[int]			=   [file for file in os.listdir(_a       ) if os.path.isfile(os.path.join(_a							,_a       )       )]

     if identifier is not None:
        _a				:	List[str]			=   [file for file in files if identifier in file]

     if n_identifier is not None:
        if isinstance(_a							,_a       ):
           for n_ in n_identifier:
              _a				:	Tuple			=   [file for file in files if n_ not in file]
        else:
           _a				:	Optional[Any]			=   [file for file in files if n_identifier not in file]

     _a				:	List[str]			=   ignore_files or []
     ignore_files.append('__init__.py'       )
     _a				:	Tuple			=   [file for file in files if file not in ignore_files]

     for file in files:
        # Open all files
        print('Testing'							,_a       )

        if only_modules:
           _a				:	Any			=   file.split('.'       )[0]
           try:
              _a				:	List[str]			=   getattr(_a							,_a       )
              _a				:	int			=   doctest.DocTestSuite(_a       )
              _a				:	Any			=   unittest.TextTestRunner().run(_a       )
              self.assertIs(len(result.failures       )							,0       )
           except AttributeError:
              logger.info(F"""{module_identifier} is not a module."""       )
        else:
           _a				:	Union[str, Any]			=   doctest.testfile(str('..' / directory / file       )							,optionflags=doctest.ELLIPSIS       )
           self.assertIs(result.failed							,0       )


  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     _a				:	int			=   Path('src/transformers'       )
     _a				:	List[Any]			=   'modeling'
     _a				:	Optional[Any]			=   [
         'modeling_ctrl.py',
         'modeling_tf_ctrl.py',
     ]
     self.analyze_directory(_a							,identifier=_a							,ignore_files=_a       )


  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     _a				:	Optional[Any]			=   Path('src/transformers'       )
     _a				:	Optional[Any]			=   'tokenization'
     self.analyze_directory(_a							,identifier=_a       )


  def   __lowercase		(		self      :     List[str]       ):


     '''simple docstring'''






     _a				:	Dict			=   Path('src/transformers'       )
     _a				:	str			=   'configuration'
     self.analyze_directory(_a							,identifier=_a       )


  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     _a				:	Tuple			=   Path('src/transformers'       )
     _a				:	List[Any]			=   ['configuration', 'modeling', 'tokenization']
     self.analyze_directory(_a							,n_identifier=_a       )


  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	List[Any]			=   Path('docs/source'       )
     _a				:	List[str]			=   ['favicon.ico']
     self.analyze_directory(_a							,ignore_files=_a							,only_modules=_a       )



