






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        snake_case_					(						__UpperCamelCase			):

						"""simple docstring"""



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




											'''simple docstring'''



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



						def 					UpperCAmelCase__				(self:				int   ,				__UpperCAmelCase:				Dict   ,				__UpperCAmelCase:				Dict      )						->    List[Any]:




											'''simple docstring'''



											if dicta == dicta:
																return True
											else:
																__a			, __a				:	Optional[Any]			=				self._remove_meta_keys(__UpperCAmelCase      )
																__a			, __a				:	int			=				self._remove_meta_keys(__UpperCAmelCase      )
																if configa == configa:
																					print(f'Warning !: Mismatch in keys {meta_keysa} and {meta_keysa}.'      )
																					return True
											return False



						def 					UpperCAmelCase__				(self:				str   ,				__UpperCAmelCase:				Dict      )						->    int:




											'''simple docstring'''



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



						@torch.no_grad()
						def 					UpperCAmelCase__				(self:				int   ,				__UpperCAmelCase:				List[Union[str, os.PathLike]]   ,				**__UpperCAmelCase:				Any      )						->    Tuple:




											'''simple docstring'''



											__a				:	Optional[Any]			=				kwargs.pop("cache_dir"   ,				__UpperCAmelCase      )
											__a				:	Optional[Any]			=				kwargs.pop("resume_download"   ,				__UpperCAmelCase      )
											__a				:	Dict			=				kwargs.pop("force_download"   ,				__UpperCAmelCase      )
											__a				:	Union[str, Any]			=				kwargs.pop("proxies"   ,				__UpperCAmelCase      )
											__a				:	Any			=				kwargs.pop("local_files_only"   ,				__UpperCAmelCase      )
											__a				:	Tuple			=				kwargs.pop("use_auth_token"   ,				__UpperCAmelCase      )
											__a				:	Any			=				kwargs.pop("revision"   ,				__UpperCAmelCase      )
											__a				:	List[Any]			=				kwargs.pop("torch_dtype"   ,				__UpperCAmelCase      )
											__a				:	str			=				kwargs.pop("device_map"   ,				__UpperCAmelCase      )

											__a				:	Optional[Any]			=				kwargs.pop("alpha"   ,				0.5      )
											__a				:	List[str]			=				kwargs.pop("interp"   ,				__UpperCAmelCase      )

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

											__a				:	Optional[Any]			=				len(__UpperCAmelCase      )
											# Ignore result from model_index_json comparision of the two checkpoints
											__a				:	Optional[int]			=				kwargs.pop("force"   ,				__UpperCAmelCase      )

											# 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[str]			=				[]
											for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
																__a				:	List[Any]			=				DiffusionPipeline.load_config(
																    __UpperCAmelCase   ,				cache_dir=__UpperCAmelCase   ,				resume_download=__UpperCAmelCase   ,				force_download=__UpperCAmelCase   ,				proxies=__UpperCAmelCase   ,				local_files_only=__UpperCAmelCase   ,				use_auth_token=__UpperCAmelCase   ,				revision=__UpperCAmelCase   ,				)
																config_dicts.append(__UpperCAmelCase      )

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

																__a				:	str			=				(
																    pretrained_model_name_or_path
																    if os.path.isdir(__UpperCAmelCase      )
																    else snapshot_download(
																        __UpperCAmelCase   ,				cache_dir=__UpperCAmelCase   ,				resume_download=__UpperCAmelCase   ,				proxies=__UpperCAmelCase   ,				local_files_only=__UpperCAmelCase   ,				use_auth_token=__UpperCAmelCase   ,				revision=__UpperCAmelCase   ,				allow_patterns=__UpperCAmelCase   ,				user_agent=__UpperCAmelCase   ,				)
																)
																print("Cached Folder"   ,				__UpperCAmelCase      )
																cached_folders.append(__UpperCAmelCase      )

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

											__a				:	List[Any]			=				None
											if len(__UpperCAmelCase      ) > 2:
																__a				:	Tuple			=				os.path.join(cached_folders[2]      )

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

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

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

																					for key in theta_a.keys():
																										if theta_a:
																															__a				:	Any			=				theta_func(theta_a[key]   ,				theta_a[key]   ,				theta_a[key]   ,				__UpperCAmelCase      )
																										else:
																															__a				:	Union[str, Any]			=				theta_func(theta_a[key]   ,				theta_a[key]   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )

																					del theta_a
																					del theta_a
																					update_theta_a(__UpperCAmelCase      )

																					del theta_a
											return final_pipe



						@staticmethod
						def 					UpperCAmelCase__				(__UpperCAmelCase:				List[Any]   ,				__UpperCAmelCase:				int   ,				__UpperCAmelCase:				List[Any]   ,				__UpperCAmelCase:				List[Any]      )						->    Optional[Any]:




											'''simple docstring'''



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



						@staticmethod
						def 					UpperCAmelCase__				(__UpperCAmelCase:				Optional[int]   ,				__UpperCAmelCase:				Tuple   ,				__UpperCAmelCase:				List[Any]   ,				__UpperCAmelCase:				int      )						->    str:




											'''simple docstring'''



											__a				:	Dict			=				alpha * alpha * (3 - (2 * alpha))
											return thetaa + ((thetaa - thetaa) * alpha)



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




											'''simple docstring'''



											import math

											__a				:	List[Any]			=				0.5 - math.sin(math.asin(1.0 - 2.0 * alpha      ) / 3.0      )
											return thetaa + ((thetaa - thetaa) * alpha)



						@staticmethod
						def 					UpperCAmelCase__				(__UpperCAmelCase:				Tuple   ,				__UpperCAmelCase:				Any   ,				__UpperCAmelCase:				Optional[int]   ,				__UpperCAmelCase:				Dict      )						->    str:




											'''simple docstring'''



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













import math







def 						a_      (__A			)							->	bool:



					"""simple docstring"""

					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(__A			) + 1			)							,					6			):
										if number % i == 0 or number % (i + 2) == 0:
															return False
					return True







def 						a_      (__A = 1_000							,					__A = 1_000			)							->	int:



					"""simple docstring"""
					__a				:	Optional[int]			=				[0, 0, 0]  # length, a, b
					for a in range((a_limit * -1) + 1							,					__A			):
										for b in range(2							,					__A			):
															if is_prime(__A			):
																				__a				:	Any			=				0
																				__a				:	List[str]			=				0
																				while is_prime((n**2) + (a * n) + b			):
																									count += 1
																									n += 1
																				if count > longest[0]:
																									__a				:	Any			=				[count, a, b]
					__a				:	str			=				longest[1] * longest[2]
					return ans


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





