




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       :     Dict ):




									"""simple docstring"""


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







			def UpperCamelCase     (			self       :     int       ,       snake_case__       :     Any       ,       snake_case__       :     Optional[int] ):




									"""simple docstring"""


									if dicta == dicta:
															return True
									else:
															_UpperCAmelCase						=	self._remove_meta_keys(_A )
															_UpperCAmelCase						=	self._remove_meta_keys(_A )
															if configa == configa:
																					print(F"""Warning !: Mismatch in keys {meta_keysa} and {meta_keysa}.""" )
																					return True
									return False







			def UpperCamelCase     (			self       :     Optional[Any]       ,       snake_case__       :     Dict ):




									"""simple docstring"""


									_UpperCAmelCase						=	[]
									_UpperCAmelCase						=	config_dict.copy()
									for key in config_dict.keys():
															if key.startswith("_" ):
																					temp_dict.pop(_A )
																					meta_keys.append(_A )
									return (temp_dict, meta_keys)







			@torch.no_grad()
			def UpperCamelCase     (			self       :     str       ,       snake_case__       :     List[Union[str, os.PathLike]]       ,       **snake_case__       :     Tuple ):




									"""simple docstring"""


									_UpperCAmelCase						=	kwargs.pop("cache_dir"       ,       _A )
									_UpperCAmelCase						=	kwargs.pop("resume_download"       ,       _A )
									_UpperCAmelCase						=	kwargs.pop("force_download"       ,       _A )
									_UpperCAmelCase						=	kwargs.pop("proxies"       ,       _A )
									_UpperCAmelCase						=	kwargs.pop("local_files_only"       ,       _A )
									_UpperCAmelCase						=	kwargs.pop("use_auth_token"       ,       _A )
									_UpperCAmelCase						=	kwargs.pop("revision"       ,       _A )
									_UpperCAmelCase						=	kwargs.pop("torch_dtype"       ,       _A )
									_UpperCAmelCase						=	kwargs.pop("device_map"       ,       _A )

									_UpperCAmelCase						=	kwargs.pop("alpha"       ,       0.5 )
									_UpperCAmelCase						=	kwargs.pop("interp"       ,       _A )

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

									_UpperCAmelCase						=	len(_A )
									# Ignore result from model_index_json comparision of the two checkpoints
									_UpperCAmelCase						=	kwargs.pop("force"       ,       _A )

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

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

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

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

									_UpperCAmelCase						=	None
									if len(_A ) > 2:
															_UpperCAmelCase						=	os.path.join(cached_folders[2] )

									if interp == "sigmoid":
															_UpperCAmelCase						=	CheckpointMergerPipeline.sigmoid
									elif interp == "inv_sigmoid":
															_UpperCAmelCase						=	CheckpointMergerPipeline.inv_sigmoid
									elif interp == "add_diff":
															_UpperCAmelCase						=	CheckpointMergerPipeline.add_difference
									else:
															_UpperCAmelCase						=	CheckpointMergerPipeline.weighted_sum

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

																											_UpperCAmelCase						=	getattr(_A       ,       "load_state_dict" )
																											_UpperCAmelCase						=	(
																											    safetensors.torch.load_file(_A )
																											    if (is_safetensors_available() and checkpoint_path_a.endswith(".safetensors" ))
																											    else torch.load(_A       ,       map_location="cpu" )
																											)
																											_UpperCAmelCase						=	None
																											if checkpoint_path_a:
																																	_UpperCAmelCase						=	(
																																	    safetensors.torch.load_file(_A )
																																	    if (is_safetensors_available() and checkpoint_path_a.endswith(".safetensors" ))
																																	    else torch.load(_A       ,       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(_A )}""" )
																											continue
																					print(F"""MERGING {attr}""" )

																					for key in theta_a.keys():
																											if theta_a:
																																	_UpperCAmelCase						=	theta_func(theta_a[key]       ,       theta_a[key]       ,       theta_a[key]       ,       _A )
																											else:
																																	_UpperCAmelCase						=	theta_func(theta_a[key]       ,       theta_a[key]       ,       _A       ,       _A )

																					del theta_a
																					del theta_a
																					update_theta_a(_A )

																					del theta_a
									return final_pipe







			@staticmethod
			def UpperCamelCase     (			snake_case__       :     Any       ,       snake_case__       :     str       ,       snake_case__       :     Tuple       ,       snake_case__       :     Tuple ):




									"""simple docstring"""


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







			@staticmethod
			def UpperCamelCase     (			snake_case__       :     List[str]       ,       snake_case__       :     Any       ,       snake_case__       :     Optional[Any]       ,       snake_case__       :     Any ):




									"""simple docstring"""


									_UpperCAmelCase						=	alpha * alpha * (3 - (2 * alpha))
									return thetaa + ((thetaa - thetaa) * alpha)







			@staticmethod
			def UpperCamelCase     (			snake_case__       :     List[Any]       ,       snake_case__       :     Any       ,       snake_case__       :     int       ,       snake_case__       :     Optional[Any] ):




									"""simple docstring"""


									import math

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







			@staticmethod
			def UpperCamelCase     (			snake_case__       :     str       ,       snake_case__       :     Tuple       ,       snake_case__       :     str       ,       snake_case__       :     Dict ):




									"""simple docstring"""


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





"""simple docstring"""







def     __UpperCAmelCase							(       UpperCAmelCase_       :							int = 1_00    )				->     int:

	'''simple docstring'''





	__snake_case     :				Any 						=					1
	__snake_case     :				Tuple 						=					0
	for i in range(1     ,				num + 1    ):
		fact *= i

	for j in str(UpperCAmelCase_    ):
		result += int(UpperCAmelCase_    )

	return result


if __name__ == "__main__":
	print(solution(int(input("Enter the Number: ").strip())))





