


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


__A :  Tuple    							=				logging.get_logger(__name__)






class        __snake_case	(       _SCREAMING_SNAKE_CASE):







    """simple docstring"""



    def __init__(       self   :  Any   ,						lowerCamelCase   :  Union[List[ControlNetModel], Tuple[ControlNetModel]]		)       ->  Tuple:
      super().__init__()
      lowerCAmelCase_      :				Optional[Any]      =       nn.ModuleList(lowerCamelCase		)

    def __lowercase       (       self   :  Dict   ,						lowerCamelCase   :  torch.FloatTensor   ,						lowerCamelCase   :  Union[torch.Tensor, float, int]   ,						lowerCamelCase   :  torch.Tensor   ,						lowerCamelCase   :  List[torch.tensor]   ,						lowerCamelCase   :  List[float]   ,						lowerCamelCase   :  Optional[torch.Tensor] = None   ,						lowerCamelCase   :  Optional[torch.Tensor] = None   ,						lowerCamelCase   :  Optional[torch.Tensor] = None   ,						lowerCamelCase   :  Optional[Dict[str, Any]] = None   ,						lowerCamelCase   :  bool = False   ,						lowerCamelCase   :  bool = True   ,						)       ->  Union[ControlNetOutput, Tuple]:
      for i, (image, scale, controlnet) in enumerate(zip(lowerCamelCase   ,						lowerCamelCase   ,						self.nets		)		):
        lowerCAmelCase_,							lowerCAmelCase_      :				Union[str, Any]      =       controlnet(
            lowerCamelCase   ,						lowerCamelCase   ,						lowerCamelCase   ,						lowerCamelCase   ,						lowerCamelCase   ,						lowerCamelCase   ,						lowerCamelCase   ,						lowerCamelCase   ,						lowerCamelCase   ,						lowerCamelCase   ,						lowerCamelCase   ,						)

        # merge samples
        if i == 0:
          lowerCAmelCase_,							lowerCAmelCase_      :				List[str]      =       down_samples, mid_sample
        else:
          lowerCAmelCase_      :				Optional[Any]      =       [
              samples_prev + samples_curr
              for samples_prev, samples_curr in zip(lowerCamelCase   ,						lowerCamelCase		)
          ]
          mid_block_res_sample += mid_sample

      return down_block_res_samples, mid_block_res_sample

    def __lowercase       (       self   :  Optional[Any]   ,						lowerCamelCase   :  Union[str, os.PathLike]   ,						lowerCamelCase   :  bool = True   ,						lowerCamelCase   :  Callable = None   ,						lowerCamelCase   :  bool = False   ,						lowerCamelCase   :  Optional[str] = None   ,						)       ->  List[str]:
      lowerCAmelCase_      :				Union[str, Any]      =       0
      lowerCAmelCase_      :				Any      =       save_directory
      for controlnet in self.nets:
        controlnet.save_pretrained(
            lowerCamelCase   ,						is_main_process=lowerCamelCase   ,						save_function=lowerCamelCase   ,						safe_serialization=lowerCamelCase   ,						variant=lowerCamelCase   ,						)

        idx += 1
        lowerCAmelCase_      :				Optional[Any]      =       model_path_to_save + F'_{idx}'





    @classmethod
    def __lowercase       (       cls   :  List[str]   ,						lowerCamelCase   :  Optional[Union[str, os.PathLike]]   ,						**lowerCamelCase   :  str		)       ->  Any:
      lowerCAmelCase_      :				int      =       0
      lowerCAmelCase_      :				Union[str, Any]      =       []

      # 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_      :				int      =       pretrained_model_path
      while os.path.isdir(lowerCamelCase		):
        lowerCAmelCase_      :				Tuple      =       ControlNetModel.from_pretrained(lowerCamelCase   ,						**lowerCamelCase		)
        controlnets.append(lowerCamelCase		)

        idx += 1
        lowerCAmelCase_      :				List[str]      =       pretrained_model_path + F'_{idx}'

      logger.info(F'{len(lowerCamelCase		)} controlnets loaded from {pretrained_model_path}.'		)

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

      return cls(lowerCamelCase		)







'''simple docstring'''






import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_lxmert import LxmertTokenizer


__A :  Any    							=				{"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

__A :  int    							=				{
    "vocab_file": {
        "unc-nlp/lxmert-base-uncased": "https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt",
    },
    "tokenizer_file": {
        "unc-nlp/lxmert-base-uncased": (
            "https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json"
        ),
    },
}

__A :  List[Any]    							=				{
    "unc-nlp/lxmert-base-uncased": 512,
}

__A :  Optional[Any]    							=				{
    "unc-nlp/lxmert-base-uncased": {"do_lower_case": True},
}






class        __snake_case	(       _SCREAMING_SNAKE_CASE):







    """simple docstring"""



    lowercase       			= VOCAB_FILES_NAMES
    lowercase       			= PRETRAINED_VOCAB_FILES_MAP
    lowercase       			= PRETRAINED_INIT_CONFIGURATION
    lowercase       			= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    lowercase       			= LxmertTokenizer

    def __init__(       self   :  Dict   ,						lowerCamelCase   :  Tuple=None   ,						lowerCamelCase   :  List[str]=None   ,						lowerCamelCase   :  Dict=True   ,						lowerCamelCase   :  List[Any]="[UNK]"   ,						lowerCamelCase   :  Tuple="[SEP]"   ,						lowerCamelCase   :  str="[PAD]"   ,						lowerCamelCase   :  Any="[CLS]"   ,						lowerCamelCase   :  str="[MASK]"   ,						lowerCamelCase   :  Dict=True   ,						lowerCamelCase   :  Union[str, Any]=None   ,						**lowerCamelCase   :  Optional[int]   ,						)       ->  Optional[Any]:
      super().__init__(
          lowerCamelCase   ,						tokenizer_file=lowerCamelCase   ,						do_lower_case=lowerCamelCase   ,						unk_token=lowerCamelCase   ,						sep_token=lowerCamelCase   ,						pad_token=lowerCamelCase   ,						cls_token=lowerCamelCase   ,						mask_token=lowerCamelCase   ,						tokenize_chinese_chars=lowerCamelCase   ,						strip_accents=lowerCamelCase   ,						**lowerCamelCase   ,						)

      lowerCAmelCase_      :				Optional[Any]      =       json.loads(self.backend_tokenizer.normalizer.__getstate__()		)
      if (
          normalizer_state.get("""lowercase"""   ,						lowerCamelCase		) != do_lower_case
          or normalizer_state.get("""strip_accents"""   ,						lowerCamelCase		) != strip_accents
          or normalizer_state.get("""handle_chinese_chars"""   ,						lowerCamelCase		) != tokenize_chinese_chars
      ):
        lowerCAmelCase_      :				Tuple      =       getattr(lowerCamelCase   ,						normalizer_state.pop("""type"""		)		)
        lowerCAmelCase_      :				Optional[Any]      =       do_lower_case
        lowerCAmelCase_      :				Dict      =       strip_accents
        lowerCAmelCase_      :				List[Any]      =       tokenize_chinese_chars
        lowerCAmelCase_      :				List[Any]      =       normalizer_class(**lowerCamelCase		)

      lowerCAmelCase_      :				Tuple      =       do_lower_case

    def __lowercase       (       self   :  Tuple   ,						lowerCamelCase   :  str   ,						lowerCamelCase   :  Optional[Any]=None		)       ->  int:
      lowerCAmelCase_      :				Any      =       [self.cls_token_id] + token_ids_a + [self.sep_token_id]

      if token_ids_a:
        output += token_ids_a + [self.sep_token_id]

      return output

    def __lowercase       (       self   :  str   ,						lowerCamelCase   :  List[int]   ,						lowerCamelCase   :  Optional[List[int]] = None		)       ->  List[int]:
      lowerCAmelCase_      :				str      =       [self.sep_token_id]
      lowerCAmelCase_      :				Optional[int]      =       [self.cls_token_id]
      if token_ids_a is None:
        return len(cls + token_ids_a + sep		) * [0]
      return len(cls + token_ids_a + sep		) * [0] + len(token_ids_a + sep		) * [1]





    def __lowercase       (       self   :  Tuple   ,						lowerCamelCase   :  str   ,						lowerCamelCase   :  Optional[str] = None		)       ->  Tuple[str]:
      lowerCAmelCase_      :				int      =       self._tokenizer.model.save(lowerCamelCase   ,						name=lowerCamelCase		)
      return tuple(lowerCamelCase		)



