
'''simple docstring'''





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 						UpperCAmelCase	(		A_				):



   def __init__(self	:      Any				)	->			Optional[int]:


          '''simple docstring'''


          self.register_to_config()
          super().__init__()



   def        _SCREAMING_SNAKE_CASE     (self	:      int					,		snake_case__	:      List[Any]					,		snake_case__	:      List[str]				)	->			int:


          '''simple docstring'''


          if dicta == dicta:
                 return True
          else:
                 snake_case :     Any           =   self._remove_meta_keys(snake_case__				)
                 snake_case :     int           =   self._remove_meta_keys(snake_case__				)
                 if configa == configa:
                        print(f"""Warning !: Mismatch in keys {meta_keysa} and {meta_keysa}."""				)
                        return True
          return False



   def        _SCREAMING_SNAKE_CASE     (self	:      List[str]					,		snake_case__	:      Dict				)	->			List[Any]:


          '''simple docstring'''


          snake_case :     Optional[Any]           =   []
          snake_case :     List[str]           =   config_dict.copy()
          for key in config_dict.keys():
                 if key.startswith("_"				):
                        temp_dict.pop(snake_case__				)
                        meta_keys.append(snake_case__				)
          return (temp_dict, meta_keys)



   @torch.no_grad()
   def        _SCREAMING_SNAKE_CASE     (self	:      int					,		snake_case__	:      List[Union[str, os.PathLike]]					,		**snake_case__	:      Optional[Any]				)	->			List[Any]:


          '''simple docstring'''


          snake_case :     Any           =   kwargs.pop("cache_dir"					,		snake_case__				)
          snake_case :     Tuple           =   kwargs.pop("resume_download"					,		snake_case__				)
          snake_case :     Any           =   kwargs.pop("force_download"					,		snake_case__				)
          snake_case :     Optional[Any]           =   kwargs.pop("proxies"					,		snake_case__				)
          snake_case :     Tuple           =   kwargs.pop("local_files_only"					,		snake_case__				)
          snake_case :     int           =   kwargs.pop("use_auth_token"					,		snake_case__				)
          snake_case :     List[str]           =   kwargs.pop("revision"					,		snake_case__				)
          snake_case :     List[Any]           =   kwargs.pop("torch_dtype"					,		snake_case__				)
          snake_case :     Optional[Any]           =   kwargs.pop("device_map"					,		snake_case__				)

          snake_case :     Union[str, Any]           =   kwargs.pop("alpha"					,		0.5				)
          snake_case :     Dict           =   kwargs.pop("interp"					,		snake_case__				)

          print("Received list"					,		snake_case__				)
          print(f"""Combining with alpha={alpha}, interpolation mode={interp}"""				)

          snake_case :     Dict           =   len(snake_case__				)
          # Ignore result from model_index_json comparision of the two checkpoints
          snake_case :     str           =   kwargs.pop("force"					,		snake_case__				)

          # 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 '_'
          snake_case :     Optional[int]           =   []
          for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
                 snake_case :     Dict           =   DiffusionPipeline.load_config(
                     snake_case__					,		cache_dir=snake_case__					,		resume_download=snake_case__					,		force_download=snake_case__					,		proxies=snake_case__					,		local_files_only=snake_case__					,		use_auth_token=snake_case__					,		revision=snake_case__					,		)
                 config_dicts.append(snake_case__				)

          snake_case :     Optional[Any]           =   True
          for idx in range(1					,		len(snake_case__				)				):
                 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.
          snake_case :     Union[str, Any]           =   []
          for pretrained_model_name_or_path, config_dict in zip(snake_case__					,		snake_case__				):
                 snake_case :     Tuple           =   [k for k in config_dict.keys() if not k.startswith("_"				)]
                 snake_case :     Optional[int]           =   [os.path.join(snake_case__					,		"*"				) for k in folder_names]
                 allow_patterns += [
                     WEIGHTS_NAME,
                     SCHEDULER_CONFIG_NAME,
                     CONFIG_NAME,
                     ONNX_WEIGHTS_NAME,
                     DiffusionPipeline.config_name,
                 ]
                 snake_case :     Any           =   config_dict.get("_class_name"				)
                 snake_case :     Optional[Any]           =   {"diffusers": __version__, "pipeline_class": requested_pipeline_class}

                 snake_case :     Optional[int]           =   (
                     pretrained_model_name_or_path
                     if os.path.isdir(snake_case__				)
                     else snapshot_download(
                         snake_case__					,		cache_dir=snake_case__					,		resume_download=snake_case__					,		proxies=snake_case__					,		local_files_only=snake_case__					,		use_auth_token=snake_case__					,		revision=snake_case__					,		allow_patterns=snake_case__					,		user_agent=snake_case__					,		)
                 )
                 print("Cached Folder"					,		snake_case__				)
                 cached_folders.append(snake_case__				)

          # Step 3:-
          # Load the first checkpoint as a diffusion pipeline and modify its module state_dict in place
          snake_case :     str           =   DiffusionPipeline.from_pretrained(
              cached_folders[0]					,		torch_dtype=snake_case__					,		device_map=snake_case__				)
          final_pipe.to(self.device				)

          snake_case :     Optional[Any]           =   None
          if len(snake_case__				) > 2:
                 snake_case :     Tuple           =   os.path.join(cached_folders[2]				)

          if interp == "sigmoid":
                 snake_case :     List[Any]           =   CheckpointMergerPipeline.sigmoid
          elif interp == "inv_sigmoid":
                 snake_case :     Union[str, Any]           =   CheckpointMergerPipeline.inv_sigmoid
          elif interp == "add_diff":
                 snake_case :     List[str]           =   CheckpointMergerPipeline.add_difference
          else:
                 snake_case :     List[str]           =   CheckpointMergerPipeline.weighted_sum

          # Find each module's state dict.
          for attr in final_pipe.config.keys():
                 if not attr.startswith("_"				):
                        snake_case :     Tuple           =   os.path.join(cached_folders[1]					,		snake_case__				)
                        if os.path.exists(snake_case__				):
                               snake_case :     Optional[int]           =   [
                                   *glob.glob(os.path.join(snake_case__					,		"*.safetensors"				)				),
                                   *glob.glob(os.path.join(snake_case__					,		"*.bin"				)				),
                               ]
                               snake_case :     Any           =   files[0] if len(snake_case__				) > 0 else None
                        if len(snake_case__				) < 3:
                               snake_case :     int           =   None
                        else:
                               snake_case :     int           =   os.path.join(cached_folders[2]					,		snake_case__				)
                               if os.path.exists(snake_case__				):
                                      snake_case :     Dict           =   [
                                          *glob.glob(os.path.join(snake_case__					,		"*.safetensors"				)				),
                                          *glob.glob(os.path.join(snake_case__					,		"*.bin"				)				),
                                      ]
                                      snake_case :     Optional[Any]           =   files[0] if len(snake_case__				) > 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:
                               snake_case :     Optional[Any]           =   getattr(snake_case__					,		snake_case__				)
                               if isinstance(snake_case__					,		snake_case__				):  # ignore requires_safety_checker boolean
                                      continue
                               snake_case :     Optional[int]           =   getattr(snake_case__					,		"state_dict"				)
                               snake_case :     Union[str, Any]           =   theta_a()

                               snake_case :     Optional[int]           =   getattr(snake_case__					,		"load_state_dict"				)
                               snake_case :     Dict           =   (
                                   safetensors.torch.load_file(snake_case__				)
                                   if (is_safetensors_available() and checkpoint_path_a.endswith(".safetensors"				))
                                   else torch.load(snake_case__					,		map_location="cpu"				)
                               )
                               snake_case :     List[Any]           =   None
                               if checkpoint_path_a:
                                      snake_case :     Tuple           =   (
                                          safetensors.torch.load_file(snake_case__				)
                                          if (is_safetensors_available() and checkpoint_path_a.endswith(".safetensors"				))
                                          else torch.load(snake_case__					,		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(snake_case__				)}"""				)
                               continue
                        print(f"""MERGING {attr}"""				)

                        for key in theta_a.keys():
                               if theta_a:
                                      snake_case :     Tuple           =   theta_func(theta_a[key]					,		theta_a[key]					,		theta_a[key]					,		snake_case__				)
                               else:
                                      snake_case :     Optional[Any]           =   theta_func(theta_a[key]					,		theta_a[key]					,		snake_case__					,		snake_case__				)

                        del theta_a
                        del theta_a
                        update_theta_a(snake_case__				)

                        del theta_a
          return final_pipe



   @staticmethod
   def        _SCREAMING_SNAKE_CASE     (snake_case__	:      str					,		snake_case__	:      int					,		snake_case__	:      List[str]					,		snake_case__	:      Optional[int]				)	->			int:


          '''simple docstring'''


          return ((1 - alpha) * thetaa) + (alpha * thetaa)



   @staticmethod
   def        _SCREAMING_SNAKE_CASE     (snake_case__	:      List[Any]					,		snake_case__	:      Optional[int]					,		snake_case__	:      int					,		snake_case__	:      Optional[int]				)	->			List[str]:


          '''simple docstring'''


          snake_case :     Any           =   alpha * alpha * (3 - (2 * alpha))
          return thetaa + ((thetaa - thetaa) * alpha)



   @staticmethod
   def        _SCREAMING_SNAKE_CASE     (snake_case__	:      Any					,		snake_case__	:      Tuple					,		snake_case__	:      Optional[Any]					,		snake_case__	:      Optional[int]				)	->			int:


          '''simple docstring'''


          import math

          snake_case :     Dict           =   0.5 - math.sin(math.asin(1.0 - 2.0 * alpha				) / 3.0				)
          return thetaa + ((thetaa - thetaa) * alpha)



   @staticmethod
   def        _SCREAMING_SNAKE_CASE     (snake_case__	:      Tuple					,		snake_case__	:      Any					,		snake_case__	:      Optional[Any]					,		snake_case__	:      List[Any]				)	->			Dict:


          '''simple docstring'''


          return thetaa + (thetaa - thetaa) * (1.0 - alpha)







import math
from itertools import permutations


def     UpperCamelCase      (					__lowerCamelCase  :				int					):

       if 1 < number < 4:
              # 2 and 3 are primes
              return True
       elif number < 2 or number % 2 == 0 or number % 3 == 0:
              # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
              return False

       # All primes number are in format of 6k +/- 1
       for i in range(5       ,      int(math.sqrt(__lowerCamelCase					) + 1					)       ,      6					):
              if number % i == 0 or number % (i + 2) == 0:
                     return False
       return True


def     UpperCamelCase      (					__lowerCamelCase  :				int       ,      __lowerCamelCase  :				list					):
       snake_case       ,      snake_case :     List[str]           =   0, len(__lowerCamelCase					) - 1
       while left <= right:
              snake_case :     int           =   (left + right) // 2
              if prime_list[middle] == target:
                     return True
              elif prime_list[middle] < target:
                     snake_case :     Dict           =   middle + 1
              else:
                     snake_case :     Optional[int]           =   middle - 1

       return False


def     UpperCamelCase      (					):
       snake_case :     List[Any]           =   [n for n in range(1001       ,      10000       ,      2					) if is_prime(__lowerCamelCase					)]
       snake_case :     Dict           =   []

       for number in prime_list:
              snake_case :     Dict           =   []

              for prime_member in permutations(list(str(__lowerCamelCase					)					)					):
                     snake_case :     Dict           =   int("".join(__lowerCamelCase					)					)

                     if prime % 2 == 0:
                            continue

                     if search(__lowerCamelCase       ,      __lowerCamelCase					):
                            tmp_numbers.append(__lowerCamelCase					)

              tmp_numbers.sort()
              if len(__lowerCamelCase					) >= 3:
                     candidates.append(__lowerCamelCase					)

       snake_case :     Union[str, Any]           =   []
       for candidate in candidates:
              snake_case :     Dict           =   len(__lowerCamelCase					)
              snake_case :     Any           =   False

              for i in range(__lowerCamelCase					):
                     for j in range(i + 1       ,      __lowerCamelCase					):
                            for k in range(j + 1       ,      __lowerCamelCase					):
                                   if (
                                       abs(candidate[i] - candidate[j]					)
                                       == abs(candidate[j] - candidate[k]					)
                                       and len({candidate[i], candidate[j], candidate[k]}					) == 3
                                   ):
                                          passed.append(
                                              sorted([candidate[i], candidate[j], candidate[k]]					)					)
                                          snake_case :     Optional[Any]           =   True

                                   if found:
                                          break
                            if found:
                                   break
                     if found:
                            break

       snake_case :     Tuple           =   set()
       for seq in passed:
              answer.add("".join([str(__lowerCamelCase					) for i in seq]					)					)

       return max(int(__lowerCamelCase					) for x in answer					)


if __name__ == "__main__":
   print(solution())





