code: 
  
  
  
  
  
  import glob
  import os
  from typing import Dict, List, Union
  
  import torch
  
  from diffusers.utils import is_safetensors_available
  
  
  if is_safetensors_available():
       import safetensors.torch
  
  from huggingface_hub import snapshot_download
  
  from diffusers import DiffusionPipeline, __version__
  from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
  from diffusers.utils import CONFIG_NAME, DIFFUSERS_CACHE, ONNX_WEIGHTS_NAME, WEIGHTS_NAME
  
  
  
  
  
  
  
  class        __lowerCAmelCase (					UpperCamelCase__):
  
  
  
  
  
  
  
        def __init__(					self							)     ->		List[str]:
  
  
  
          '''simple docstring'''
  
  
  
  
          self.register_to_config()
          super().__init__()
  
  
  
  
  
  
  
        def      _lowercase						(					self	,   lowerCAmelCase__	,   lowerCAmelCase__							)     ->		int:
  
  
  
          '''simple docstring'''
  
  
  
  
          if dicta == dicta:
            return True
          else:
            a__			:      Tuple            =self._remove_meta_keys(lowerCAmelCase__							)
            a__			:      str            =self._remove_meta_keys(lowerCAmelCase__							)
            if configa == configa:
              print(F'''Warning !: Mismatch in keys {meta_keysa} and {meta_keysa}.'''							)
              return True
          return False
  
  
  
  
  
  
  
        def      _lowercase						(					self	,   lowerCAmelCase__							)     ->		Tuple:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Dict            =[]
          a__			:      List[str]            =config_dict.copy()
          for key in config_dict.keys():
            if key.startswith("_"							):
              temp_dict.pop(lowerCAmelCase__							)
              meta_keys.append(lowerCAmelCase__							)
          return (temp_dict, meta_keys)
  
  
  
  
  
  
  
        @torch.no_grad()
        def      _lowercase						(					self	,   lowerCAmelCase__	,   **lowerCAmelCase__							)     ->		Optional[int]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Dict            =kwargs.pop("cache_dir"	,   lowerCAmelCase__							)
          a__			:      Dict            =kwargs.pop("resume_download"	,   lowerCAmelCase__							)
          a__			:      Optional[Any]            =kwargs.pop("force_download"	,   lowerCAmelCase__							)
          a__			:      Tuple            =kwargs.pop("proxies"	,   lowerCAmelCase__							)
          a__			:      Dict            =kwargs.pop("local_files_only"	,   lowerCAmelCase__							)
          a__			:      List[Any]            =kwargs.pop("use_auth_token"	,   lowerCAmelCase__							)
          a__			:      int            =kwargs.pop("revision"	,   lowerCAmelCase__							)
          a__			:      int            =kwargs.pop("torch_dtype"	,   lowerCAmelCase__							)
          a__			:      List[str]            =kwargs.pop("device_map"	,   lowerCAmelCase__							)
  
          a__			:      Union[str, Any]            =kwargs.pop("alpha"	,   0.5							)
          a__			:      Any            =kwargs.pop("interp"	,   lowerCAmelCase__							)
  
          print("Received list"	,   lowerCAmelCase__							)
          print(F'''Combining with alpha={alpha}, interpolation mode={interp}'''							)
  
          a__			:      List[str]            =len(lowerCAmelCase__							)
          # Ignore result from model_index_json comparision of the two checkpoints
          a__			:      Dict            =kwargs.pop("force"	,   lowerCAmelCase__							)
  
          # If less than 2 checkpoints, nothing to merge. If more than 3, not supported for now.
          if checkpoint_count > 3 or checkpoint_count < 2:
            raise ValueError(
                "Received incorrect number of checkpoints to merge. Ensure that either 2 or 3 checkpoints are being"
                " passed."							)
  
          print("Received the right number of checkpoints"							)
          # chkpt0, chkpt1 = pretrained_model_name_or_path_list[0:2]
          # chkpt2 = pretrained_model_name_or_path_list[2] if checkpoint_count == 3 else None
  
          # Validate that the checkpoints can be merged
          # Step 1: Load the model config and compare the checkpoints. We'll compare the model_index.json first while ignoring the keys starting with '_'
          a__			:      List[Any]            =[]
          for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
            a__			:      int            =DiffusionPipeline.load_config(
                lowerCAmelCase__	,   cache_dir=lowerCAmelCase__	,   resume_download=lowerCAmelCase__	,   force_download=lowerCAmelCase__	,   proxies=lowerCAmelCase__	,   local_files_only=lowerCAmelCase__	,   use_auth_token=lowerCAmelCase__	,   revision=lowerCAmelCase__	,   )
            config_dicts.append(lowerCAmelCase__							)
  
          a__			:      Tuple            =True
          for idx in range(1	,   len(lowerCAmelCase__							)							):
            comparison_result &= self._compare_model_configs(config_dicts[idx - 1]	,   config_dicts[idx]							)
            if not force and comparison_result is False:
              raise ValueError("Incompatible checkpoints. Please check model_index.json for the models."							)
              print(config_dicts[0]	,   config_dicts[1]							)
          print("Compatible model_index.json files found"							)
          # Step 2: Basic Validation has succeeded. Let's download the models and save them into our local files.
          a__			:      List[str]            =[]
          for pretrained_model_name_or_path, config_dict in zip(lowerCAmelCase__	,   lowerCAmelCase__							):
            a__			:      int            =[k for k in config_dict.keys() if not k.startswith("_"							)]
            a__			:      Dict            =[os.path.join(lowerCAmelCase__	,   "*"							) for k in folder_names]
            allow_patterns += [
                WEIGHTS_NAME,
                SCHEDULER_CONFIG_NAME,
                CONFIG_NAME,
                ONNX_WEIGHTS_NAME,
                DiffusionPipeline.config_name,
            ]
            a__			:      Dict            =config_dict.get("_class_name"							)
            a__			:      Optional[int]            ={"diffusers": __version__, "pipeline_class": requested_pipeline_class}
  
            a__			:      List[str]            =(
                pretrained_model_name_or_path
                if os.path.isdir(lowerCAmelCase__							)
                else snapshot_download(
                    lowerCAmelCase__	,   cache_dir=lowerCAmelCase__	,   resume_download=lowerCAmelCase__	,   proxies=lowerCAmelCase__	,   local_files_only=lowerCAmelCase__	,   use_auth_token=lowerCAmelCase__	,   revision=lowerCAmelCase__	,   allow_patterns=lowerCAmelCase__	,   user_agent=lowerCAmelCase__	,   )
            )
            print("Cached Folder"	,   lowerCAmelCase__							)
            cached_folders.append(lowerCAmelCase__							)
  
          # Step 3:-
          # Load the first checkpoint as a diffusion pipeline and modify its module state_dict in place
          a__			:      Any            =DiffusionPipeline.from_pretrained(
              cached_folders[0]	,   torch_dtype=lowerCAmelCase__	,   device_map=lowerCAmelCase__							)
          final_pipe.to(self.device							)
  
          a__			:      List[str]            =None
          if len(lowerCAmelCase__							) > 2:
            a__			:      Any            =os.path.join(cached_folders[2]							)
  
          if interp == "sigmoid":
            a__			:      Union[str, Any]            =CheckpointMergerPipeline.sigmoid
          elif interp == "inv_sigmoid":
            a__			:      Optional[int]            =CheckpointMergerPipeline.inv_sigmoid
          elif interp == "add_diff":
            a__			:      Any            =CheckpointMergerPipeline.add_difference
          else:
            a__			:      Tuple            =CheckpointMergerPipeline.weighted_sum
  
          # Find each module's state dict.
          for attr in final_pipe.config.keys():
            if not attr.startswith("_"							):
              a__			:      int            =os.path.join(cached_folders[1]	,   lowerCAmelCase__							)
              if os.path.exists(lowerCAmelCase__							):
                a__			:      str            =[
                    *glob.glob(os.path.join(lowerCAmelCase__	,   "*.safetensors"							)							),
                    *glob.glob(os.path.join(lowerCAmelCase__	,   "*.bin"							)							),
                ]
                a__			:      str            =files[0] if len(lowerCAmelCase__							) > 0 else None
              if len(lowerCAmelCase__							) < 3:
                a__			:      Union[str, Any]            =None
              else:
                a__			:      Dict            =os.path.join(cached_folders[2]	,   lowerCAmelCase__							)
                if os.path.exists(lowerCAmelCase__							):
                  a__			:      List[Any]            =[
                      *glob.glob(os.path.join(lowerCAmelCase__	,   "*.safetensors"							)							),
                      *glob.glob(os.path.join(lowerCAmelCase__	,   "*.bin"							)							),
                  ]
                  a__			:      Optional[Any]            =files[0] if len(lowerCAmelCase__							) > 0 else None
                  # For an attr if both checkpoint_path_1 and 2 are None, ignore.
                  # If atleast one is present, deal with it according to interp method, of course only if the state_dict keys match.
              if checkpoint_path_a is None and checkpoint_path_a is None:
                print(F'''Skipping {attr}: not present in 2nd or 3d model'''							)
                continue
              try:
                a__			:      Union[str, Any]            =getattr(lowerCAmelCase__	,   lowerCAmelCase__							)
                if isinstance(lowerCAmelCase__	,   lowerCAmelCase__							):  # ignore requires_safety_checker boolean
                  continue
                a__			:      Tuple            =getattr(lowerCAmelCase__	,   "state_dict"							)
                a__			:      List[Any]            =theta_a()
  
                a__			:      Any            =getattr(lowerCAmelCase__	,   "load_state_dict"							)
                a__			:      List[str]            =(
                    safetensors.torch.load_file(lowerCAmelCase__							)
                    if (is_safetensors_available() and checkpoint_path_a.endswith(".safetensors"							))
                    else torch.load(lowerCAmelCase__	,   map_location="cpu"							)
                )
                a__			:      Tuple            =None
                if checkpoint_path_a:
                  a__			:      str            =(
                      safetensors.torch.load_file(lowerCAmelCase__							)
                      if (is_safetensors_available() and checkpoint_path_a.endswith(".safetensors"							))
                      else torch.load(lowerCAmelCase__	,   map_location="cpu"							)
                  )
  
                if not theta_a.keys() == theta_a.keys():
                  print(F'''Skipping {attr}: key mismatch'''							)
                  continue
                if theta_a and not theta_a.keys() == theta_a.keys():
                  print(F'''Skipping {attr}:y mismatch'''							)
              except Exception as e:
                print(F'''Skipping {attr} do to an unexpected error: {str(lowerCAmelCase__							)}'''							)
                continue
              print(F'''MERGING {attr}'''							)
  
              for key in theta_a.keys():
                if theta_a:
                  a__			:      Dict            =theta_func(theta_a[key]	,   theta_a[key]	,   theta_a[key]	,   lowerCAmelCase__							)
                else:
                  a__			:      Dict            =theta_func(theta_a[key]	,   theta_a[key]	,   lowerCAmelCase__	,   lowerCAmelCase__							)
  
              del theta_a
              del theta_a
              update_theta_a(lowerCAmelCase__							)
  
              del theta_a
          return final_pipe
  
  
  
  
  
  
  
        @staticmethod
        def      _lowercase						(					lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)     ->		Union[str, Any]:
  
  
  
          '''simple docstring'''
  
  
  
  
          return ((1 - alpha) * thetaa) + (alpha * thetaa)
  
  
  
  
  
  
  
        @staticmethod
        def      _lowercase						(					lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)     ->		List[str]:
  
  
  
          '''simple docstring'''
  
  
  
  
          a__			:      Any            =alpha * alpha * (3 - (2 * alpha))
          return thetaa + ((thetaa - thetaa) * alpha)
  
  
  
  
  
  
  
        @staticmethod
        def      _lowercase						(					lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)     ->		str:
  
  
  
          '''simple docstring'''
  
  
  
  
          import math
  
          a__			:      Dict            =0.5 - math.sin(math.asin(1.0 - 2.0 * alpha							) / 3.0							)
          return thetaa + ((thetaa - thetaa) * alpha)
  
  
  
  
  
  
  
        @staticmethod
        def      _lowercase						(					lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__	,   lowerCAmelCase__							)     ->		str:
  
  
  
          '''simple docstring'''
  
  
  
  
          return thetaa + (thetaa - thetaa) * (1.0 - alpha)
  
  
  
  
  
  
  
style_context: 
  
  
  
  
  
  from __future__ import annotations
  def   _A (	SCREAMING_SNAKE_CASE  :     str , SCREAMING_SNAKE_CASE  :     dict[str, str]		):
  
  
  
  
  
    """simple docstring"""
  
  
  
    a__      ,							a__      ,							a__			:      Optional[int]            ="", "", ""
    a__			:      str            =[]
  
    for character in message_part:
      tmp.append(character_to_number[character]		)
  
    for each in tmp:
      one += each[0]
      two += each[1]
      three += each[2]
  
    return one + two + three
  def   _A (	SCREAMING_SNAKE_CASE  :     str , SCREAMING_SNAKE_CASE  :     dict[str, str]		):
  
  
  
  
  
    """simple docstring"""
  
  
  
    a__      ,							a__			:      Any            ="", ""
    a__			:      Optional[int]            =[]
  
    for character in message_part:
      this_part += character_to_number[character]
  
    for digit in this_part:
      tmp += digit
      if len(SCREAMING_SNAKE_CASE		) == len(SCREAMING_SNAKE_CASE		):
        result.append(SCREAMING_SNAKE_CASE		)
        a__			:      str            =""
  
    return result[0], result[1], result[2]
  def   _A (	SCREAMING_SNAKE_CASE  :     str , SCREAMING_SNAKE_CASE  :     str		):
  
  
  
  
  
    """simple docstring"""
  
  
  
    a__			:      Optional[Any]            =alphabet.replace(" " , ""		).upper()
    a__			:      List[str]            =message.replace(" " , ""		).upper()
  
    # Check length and characters
    if len(SCREAMING_SNAKE_CASE		) != 27:
      raise KeyError("Length of alphabet has to be 27."		)
    for each in message:
      if each not in alphabet:
        raise ValueError("Each message character has to be included in alphabet!"		)
  
      # Generate dictionares
    a__			:      Any            =(
        "111",
        "112",
        "113",
        "121",
        "122",
        "123",
        "131",
        "132",
        "133",
        "211",
        "212",
        "213",
        "221",
        "222",
        "223",
        "231",
        "232",
        "233",
        "311",
        "312",
        "313",
        "321",
        "322",
        "323",
        "331",
        "332",
        "333",
    )
    a__			:      Tuple            ={}
    a__			:      List[str]            ={}
    for letter, number in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		):
      a__			:      Dict            =number
      a__			:      Union[str, Any]            =letter
  
    return message, alphabet, character_to_number, number_to_character
  def   _A (	SCREAMING_SNAKE_CASE  :     str , SCREAMING_SNAKE_CASE  :     str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ." , SCREAMING_SNAKE_CASE  :     int = 5		):
  
  
  
  
  
    """simple docstring"""
  
  
  
    a__      ,							a__      ,							a__      ,							a__			:      Union[str, Any]            =__prepare(
        SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)
    a__      ,							a__			:      Union[str, Any]            ="", ""
  
    for i in range(0 , len(SCREAMING_SNAKE_CASE		) + 1 , SCREAMING_SNAKE_CASE		):
      encrypted_numeric += __encrypt_part(
          message[i : i + period] , SCREAMING_SNAKE_CASE		)
  
    for i in range(0 , len(SCREAMING_SNAKE_CASE		) , 3		):
      encrypted += number_to_character[encrypted_numeric[i : i + 3]]
  
    return encrypted
  def   _A (	SCREAMING_SNAKE_CASE  :     str , SCREAMING_SNAKE_CASE  :     str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ." , SCREAMING_SNAKE_CASE  :     int = 5		):
  
  
  
  
  
    """simple docstring"""
  
  
  
    a__      ,							a__      ,							a__      ,							a__			:      Dict            =__prepare(
        SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE		)
    a__			:      Optional[Any]            =[]
    a__			:      Any            =""
  
    for i in range(0 , len(SCREAMING_SNAKE_CASE		) + 1 , SCREAMING_SNAKE_CASE		):
      a__      ,							a__      ,							a__			:      Union[str, Any]            =__decrypt_part(message[i : i + period] , SCREAMING_SNAKE_CASE		)
  
      for j in range(0 , len(SCREAMING_SNAKE_CASE		)		):
        decrypted_numeric.append(a[j] + b[j] + c[j]		)
  
    for each in decrypted_numeric:
      decrypted += number_to_character[each]
  
    return decrypted
  
  
  if __name__ == "__main__":
       UpperCAmelCase			:			List[str]	  = """DEFEND THE EAST WALL OF THE CASTLE."""
       UpperCAmelCase			:			Optional[Any]	  = encrypt_message(msg, """EPSDUCVWYM.ZLKXNBTFGORIJHAQ""")
       UpperCAmelCase			:			Optional[int]	  = decrypt_message(encrypted, """EPSDUCVWYM.ZLKXNBTFGORIJHAQ""")
       print(F"""Encrypted: {encrypted}\nDecrypted: {decrypted}""")
  
  
  
  
  
  
  