


import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.semantic_stable_diffusion import SemanticStableDiffusionPipeline as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()






class    UpperCamelCase    (						unittest.TestCase   ):


   '''simple docstring'''







   def 						UpperCamelCase     (   self						):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()
   @property
   def 						UpperCamelCase     (   self						):
        lowercase_				:Optional[int]       			=				1
        lowercase_				:List[str]       			=				3
        lowercase_				:Optional[Any]       			=				(32, 32)

        lowercase_				:int       			=				floats_tensor((batch_size, num_channels) + sizes      ,							rng=random.Random(0						)						).to(SCREAMING_SNAKE_CASE__						)
        return image
   @property
   def 						UpperCamelCase     (   self						):
        torch.manual_seed(0						)
        lowercase_				:int       			=				UNetaDConditionModel(
            block_out_channels=(32, 64)      ,							layers_per_block=2      ,							sample_size=32      ,							in_channels=4      ,							out_channels=4      ,							down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')      ,							up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')      ,							cross_attention_dim=32      ,							)
        return model
   @property
   def 						UpperCamelCase     (   self						):
        torch.manual_seed(0						)
        lowercase_				:List[Any]       			=				AutoencoderKL(
            block_out_channels=[32, 64]      ,							in_channels=3      ,							out_channels=3      ,							down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']      ,							up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']      ,							latent_channels=4      ,							)
        return model
   @property
   def 						UpperCamelCase     (   self						):
        torch.manual_seed(0						)
        lowercase_				:Any       			=				CLIPTextConfig(
            bos_token_id=0      ,							eos_token_id=2      ,							hidden_size=32      ,							intermediate_size=37      ,							layer_norm_eps=1E-05      ,							num_attention_heads=4      ,							num_hidden_layers=5      ,							pad_token_id=1      ,							vocab_size=1000      ,							)
        return CLIPTextModel(SCREAMING_SNAKE_CASE__						)
   @property
   def 						UpperCamelCase     (   self						):
        def extract(*UpperCamelCase_      ,							**UpperCamelCase_						):






             class    UpperCamelCase    :


                '''simple docstring'''







                def __init__(   self						):
                     lowercase_				:Union[str, Any]       			=				torch.ones([0]						)




                def 						UpperCamelCase     (   self      ,							UpperCamelCase_						):
                     self.pixel_values.to(SCREAMING_SNAKE_CASE__						)
                     return self
             return Out()

        return extract
   def 						UpperCamelCase     (   self						):
        lowercase_				:Optional[Any]       			=				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
        lowercase_				:Optional[Any]       			=				self.dummy_cond_unet
        lowercase_				:int       			=				DDIMScheduler(
            beta_start=0.0_0085      ,							beta_end=0.012      ,							beta_schedule='''scaled_linear'''      ,							clip_sample=SCREAMING_SNAKE_CASE__      ,							set_alpha_to_one=SCREAMING_SNAKE_CASE__      ,							)

        lowercase_				:List[Any]       			=				self.dummy_vae
        lowercase_				:Optional[Any]       			=				self.dummy_text_encoder
        lowercase_				:int       			=				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

        # make sure here that pndm scheduler skips prk
        lowercase_				:Union[str, Any]       			=				StableDiffusionPipeline(
            unet=SCREAMING_SNAKE_CASE__      ,							scheduler=SCREAMING_SNAKE_CASE__      ,							vae=SCREAMING_SNAKE_CASE__      ,							text_encoder=SCREAMING_SNAKE_CASE__      ,							tokenizer=SCREAMING_SNAKE_CASE__      ,							safety_checker=SCREAMING_SNAKE_CASE__      ,							feature_extractor=self.dummy_extractor      ,							)
        lowercase_				:Union[str, Any]       			=				sd_pipe.to(SCREAMING_SNAKE_CASE__						)
        sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

        lowercase_				:Optional[int]       			=				'''A painting of a squirrel eating a burger'''

        lowercase_				:Optional[int]       			=				torch.Generator(device=SCREAMING_SNAKE_CASE__						).manual_seed(0						)
        lowercase_				:int       			=				sd_pipe([prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=6.0      ,							num_inference_steps=2      ,							output_type='''np'''						)
        lowercase_				:Union[str, Any]       			=				output.images

        lowercase_				:Optional[Any]       			=				torch.Generator(device=SCREAMING_SNAKE_CASE__						).manual_seed(0						)
        lowercase_				:Dict       			=				sd_pipe(
            [prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=6.0      ,							num_inference_steps=2      ,							output_type='''np'''      ,							return_dict=SCREAMING_SNAKE_CASE__      ,							)[0]

        lowercase_				:Tuple       			=				image[0, -3:, -3:, -1]
        lowercase_				:Dict       			=				image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        lowercase_				:Any       			=				np.array([0.5753, 0.6114, 0.5001, 0.5034, 0.5470, 0.4729, 0.4971, 0.4867, 0.4867]						)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2
        assert np.abs(image_from_tuple_slice.flatten() - expected_slice						).max() < 1E-2
   def 						UpperCamelCase     (   self						):
        lowercase_				:Any       			=				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
        lowercase_				:Union[str, Any]       			=				self.dummy_cond_unet
        lowercase_				:List[Any]       			=				PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE__						)
        lowercase_				:Optional[int]       			=				self.dummy_vae
        lowercase_				:Union[str, Any]       			=				self.dummy_text_encoder
        lowercase_				:List[Any]       			=				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

        # make sure here that pndm scheduler skips prk
        lowercase_				:List[Any]       			=				StableDiffusionPipeline(
            unet=SCREAMING_SNAKE_CASE__      ,							scheduler=SCREAMING_SNAKE_CASE__      ,							vae=SCREAMING_SNAKE_CASE__      ,							text_encoder=SCREAMING_SNAKE_CASE__      ,							tokenizer=SCREAMING_SNAKE_CASE__      ,							safety_checker=SCREAMING_SNAKE_CASE__      ,							feature_extractor=self.dummy_extractor      ,							)
        lowercase_				:Tuple       			=				sd_pipe.to(SCREAMING_SNAKE_CASE__						)
        sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

        lowercase_				:Optional[int]       			=				'''A painting of a squirrel eating a burger'''
        lowercase_				:Optional[int]       			=				torch.Generator(device=SCREAMING_SNAKE_CASE__						).manual_seed(0						)
        lowercase_				:Any       			=				sd_pipe([prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=6.0      ,							num_inference_steps=2      ,							output_type='''np'''						)

        lowercase_				:Any       			=				output.images

        lowercase_				:Any       			=				torch.Generator(device=SCREAMING_SNAKE_CASE__						).manual_seed(0						)
        lowercase_				:Union[str, Any]       			=				sd_pipe(
            [prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=6.0      ,							num_inference_steps=2      ,							output_type='''np'''      ,							return_dict=SCREAMING_SNAKE_CASE__      ,							)[0]

        lowercase_				:Tuple       			=				image[0, -3:, -3:, -1]
        lowercase_				:List[str]       			=				image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        lowercase_				:List[Any]       			=				np.array([0.5122, 0.5712, 0.4825, 0.5053, 0.5646, 0.4769, 0.5179, 0.4894, 0.4994]						)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2
        assert np.abs(image_from_tuple_slice.flatten() - expected_slice						).max() < 1E-2
   def 						UpperCamelCase     (   self						):
        lowercase_				:Optional[int]       			=				StableDiffusionPipeline.from_pretrained(
            '''hf-internal-testing/tiny-stable-diffusion-lms-pipe'''      ,							safety_checker=SCREAMING_SNAKE_CASE__						)
        assert isinstance(SCREAMING_SNAKE_CASE__      ,							SCREAMING_SNAKE_CASE__						)
        assert isinstance(pipe.scheduler      ,							SCREAMING_SNAKE_CASE__						)
        assert pipe.safety_checker is None

        lowercase_				:List[str]       			=				pipe('''example prompt'''      ,							num_inference_steps=2						).images[0]
        assert image is not None

        # check that there's no error when saving a pipeline with one of the models being None
        with tempfile.TemporaryDirectory() as tmpdirname:
             pipe.save_pretrained(SCREAMING_SNAKE_CASE__						)
             lowercase_				:Tuple       			=				StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE__						)

        # sanity check that the pipeline still works
        assert pipe.safety_checker is None
        lowercase_				:List[str]       			=				pipe('''example prompt'''      ,							num_inference_steps=2						).images[0]
        assert image is not None




   @unittest.skipIf(torch_device != '''cuda'''      ,							'''This test requires a GPU'''						)
   def 						UpperCamelCase     (   self						):
        lowercase_				:Optional[Any]       			=				self.dummy_cond_unet
        lowercase_				:Dict       			=				PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE__						)
        lowercase_				:List[Any]       			=				self.dummy_vae
        lowercase_				:List[Any]       			=				self.dummy_text_encoder
        lowercase_				:List[Any]       			=				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

        # put models in fp16
        lowercase_				:Optional[Any]       			=				unet.half()
        lowercase_				:List[str]       			=				vae.half()
        lowercase_				:Optional[int]       			=				bert.half()

        # make sure here that pndm scheduler skips prk
        lowercase_				:List[Any]       			=				StableDiffusionPipeline(
            unet=SCREAMING_SNAKE_CASE__      ,							scheduler=SCREAMING_SNAKE_CASE__      ,							vae=SCREAMING_SNAKE_CASE__      ,							text_encoder=SCREAMING_SNAKE_CASE__      ,							tokenizer=SCREAMING_SNAKE_CASE__      ,							safety_checker=SCREAMING_SNAKE_CASE__      ,							feature_extractor=self.dummy_extractor      ,							)
        lowercase_				:Union[str, Any]       			=				sd_pipe.to(SCREAMING_SNAKE_CASE__						)
        sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

        lowercase_				:List[str]       			=				'''A painting of a squirrel eating a burger'''
        lowercase_				:Union[str, Any]       			=				sd_pipe([prompt]      ,							num_inference_steps=2      ,							output_type='''np'''						).images

        assert image.shape == (1, 64, 64, 3)






@nightly
@require_torch_gpu
class    UpperCamelCase    (						unittest.TestCase   ):


   '''simple docstring'''







   def 						UpperCamelCase     (   self						):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()
   def 						UpperCamelCase     (   self						):
        lowercase_				:Dict       			=				'''cuda'''
        lowercase_				:str       			=				StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''						)
        lowercase_				:Any       			=				pipe.to(SCREAMING_SNAKE_CASE__						)
        pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

        lowercase_				:Optional[Any]       			=				'''a photo of a cat'''
        lowercase_				:List[str]       			=				{
            '''editing_prompt''': ['''sunglasses'''],
            '''reverse_editing_direction''': [False],
            '''edit_warmup_steps''': 10,
            '''edit_guidance_scale''': 6,
            '''edit_threshold''': 0.95,
            '''edit_momentum_scale''': 0.5,
            '''edit_mom_beta''': 0.6,
        }

        lowercase_				:int       			=				3
        lowercase_				:str       			=				7

        # no sega enabled
        lowercase_				:List[str]       			=				torch.Generator(SCREAMING_SNAKE_CASE__						)
        generator.manual_seed(SCREAMING_SNAKE_CASE__						)
        lowercase_				:Optional[int]       			=				pipe(
            [prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=SCREAMING_SNAKE_CASE__      ,							num_inference_steps=50      ,							output_type='''np'''      ,							width=512      ,							height=512      ,							)

        lowercase_				:List[str]       			=				output.images
        lowercase_				:Union[str, Any]       			=				image[0, -3:, -3:, -1]
        lowercase_				:Optional[int]       			=				[
            0.3467_3113,
            0.3849_2733,
            0.3759_7352,
            0.3408_6335,
            0.3565_0748,
            0.3557_9205,
            0.338_4763,
            0.3434_0236,
            0.357_3271,
        ]

        assert image.shape == (1, 512, 512, 3)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2

        # with sega enabled
        # generator = torch.manual_seed(seed)
        generator.manual_seed(SCREAMING_SNAKE_CASE__						)
        lowercase_				:List[Any]       			=				pipe(
            [prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=SCREAMING_SNAKE_CASE__      ,							num_inference_steps=50      ,							output_type='''np'''      ,							width=512      ,							height=512      ,							**SCREAMING_SNAKE_CASE__      ,							)

        lowercase_				:Tuple       			=				output.images
        lowercase_				:str       			=				image[0, -3:, -3:, -1]
        lowercase_				:int       			=				[
            0.4188_7826,
            0.3772_8766,
            0.3013_8272,
            0.4141_6335,
            0.4166_4985,
            0.3628_3392,
            0.3619_1246,
            0.4336_4465,
            0.4300_1732,
        ]

        assert image.shape == (1, 512, 512, 3)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2
   def 						UpperCamelCase     (   self						):
        lowercase_				:Tuple       			=				'''cuda'''
        lowercase_				:List[Any]       			=				StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''						)
        lowercase_				:Any       			=				pipe.to(SCREAMING_SNAKE_CASE__						)
        pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

        lowercase_				:str       			=				'''an image of a crowded boulevard, realistic, 4k'''
        lowercase_				:List[str]       			=				{
            '''editing_prompt''': '''crowd, crowded, people''',
            '''reverse_editing_direction''': True,
            '''edit_warmup_steps''': 10,
            '''edit_guidance_scale''': 8.3,
            '''edit_threshold''': 0.9,
            '''edit_momentum_scale''': 0.5,
            '''edit_mom_beta''': 0.6,
        }

        lowercase_				:Optional[int]       			=				9
        lowercase_				:Tuple       			=				7

        # no sega enabled
        lowercase_				:int       			=				torch.Generator(SCREAMING_SNAKE_CASE__						)
        generator.manual_seed(SCREAMING_SNAKE_CASE__						)
        lowercase_				:List[Any]       			=				pipe(
            [prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=SCREAMING_SNAKE_CASE__      ,							num_inference_steps=50      ,							output_type='''np'''      ,							width=512      ,							height=512      ,							)

        lowercase_				:List[str]       			=				output.images
        lowercase_				:Any       			=				image[0, -3:, -3:, -1]
        lowercase_				:Dict       			=				[
            0.4349_7998,
            0.9181_4065,
            0.754_0739,
            0.5558_0205,
            0.846_7265,
            0.538_9691,
            0.6257_4506,
            0.5889_7763,
            0.5092_6757,
        ]

        assert image.shape == (1, 512, 512, 3)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2

        # with sega enabled
        # generator = torch.manual_seed(seed)
        generator.manual_seed(SCREAMING_SNAKE_CASE__						)
        lowercase_				:Any       			=				pipe(
            [prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=SCREAMING_SNAKE_CASE__      ,							num_inference_steps=50      ,							output_type='''np'''      ,							width=512      ,							height=512      ,							**SCREAMING_SNAKE_CASE__      ,							)

        lowercase_				:List[Any]       			=				output.images
        lowercase_				:Optional[Any]       			=				image[0, -3:, -3:, -1]
        lowercase_				:List[str]       			=				[
            0.308_9719,
            0.3050_0144,
            0.2901_6042,
            0.3063_0964,
            0.32_5687,
            0.2941_9225,
            0.290_8091,
            0.2872_3598,
            0.2769_6294,
        ]

        assert image.shape == (1, 512, 512, 3)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2
   def 						UpperCamelCase     (   self						):
        lowercase_				:Tuple       			=				'''cuda'''
        lowercase_				:Union[str, Any]       			=				StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''						)
        lowercase_				:str       			=				pipe.to(SCREAMING_SNAKE_CASE__						)
        pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

        lowercase_				:List[str]       			=				'''a castle next to a river'''
        lowercase_				:Dict       			=				{
            '''editing_prompt''': ['''boat on a river, boat''', '''monet, impression, sunrise'''],
            '''reverse_editing_direction''': False,
            '''edit_warmup_steps''': [15, 18],
            '''edit_guidance_scale''': 6,
            '''edit_threshold''': [0.9, 0.8],
            '''edit_momentum_scale''': 0.5,
            '''edit_mom_beta''': 0.6,
        }

        lowercase_				:Any       			=				48
        lowercase_				:List[Any]       			=				7

        # no sega enabled
        lowercase_				:Optional[int]       			=				torch.Generator(SCREAMING_SNAKE_CASE__						)
        generator.manual_seed(SCREAMING_SNAKE_CASE__						)
        lowercase_				:Optional[int]       			=				pipe(
            [prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=SCREAMING_SNAKE_CASE__      ,							num_inference_steps=50      ,							output_type='''np'''      ,							width=512      ,							height=512      ,							)

        lowercase_				:Any       			=				output.images
        lowercase_				:int       			=				image[0, -3:, -3:, -1]
        lowercase_				:Optional[int]       			=				[
            0.7516_3555,
            0.7603_7145,
            0.6_1785,
            0.918_9673,
            0.862_7701,
            0.8518_9694,
            0.851_2813,
            0.8701_2076,
            0.831_2857,
        ]

        assert image.shape == (1, 512, 512, 3)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2

        # with sega enabled
        # generator = torch.manual_seed(seed)
        generator.manual_seed(SCREAMING_SNAKE_CASE__						)
        lowercase_				:str       			=				pipe(
            [prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=SCREAMING_SNAKE_CASE__      ,							num_inference_steps=50      ,							output_type='''np'''      ,							width=512      ,							height=512      ,							**SCREAMING_SNAKE_CASE__      ,							)

        lowercase_				:Optional[int]       			=				output.images
        lowercase_				:Union[str, Any]       			=				image[0, -3:, -3:, -1]
        lowercase_				:Optional[int]       			=				[
            0.7355_3365,
            0.753_7271,
            0.7434_1905,
            0.6648_0356,
            0.647_2925,
            0.6303_9416,
            0.6481_2905,
            0.674_9717,
            0.651_7102,
        ]

        assert image.shape == (1, 512, 512, 3)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2




   def 						UpperCamelCase     (   self						):
        lowercase_				:List[str]       			=				'''cuda'''
        lowercase_				:int       			=				StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''      ,							torch_dtype=torch.floataa						)
        lowercase_				:Union[str, Any]       			=				pipe.to(SCREAMING_SNAKE_CASE__						)
        pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__						)

        lowercase_				:Any       			=				'''a photo of a cat'''
        lowercase_				:Union[str, Any]       			=				{
            '''editing_prompt''': ['''sunglasses'''],
            '''reverse_editing_direction''': [False],
            '''edit_warmup_steps''': 10,
            '''edit_guidance_scale''': 6,
            '''edit_threshold''': 0.95,
            '''edit_momentum_scale''': 0.5,
            '''edit_mom_beta''': 0.6,
        }

        lowercase_				:Dict       			=				3
        lowercase_				:Optional[int]       			=				7

        # no sega enabled
        lowercase_				:List[Any]       			=				torch.Generator(SCREAMING_SNAKE_CASE__						)
        generator.manual_seed(SCREAMING_SNAKE_CASE__						)
        lowercase_				:Any       			=				pipe(
            [prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=SCREAMING_SNAKE_CASE__      ,							num_inference_steps=50      ,							output_type='''np'''      ,							width=512      ,							height=512      ,							)

        lowercase_				:Any       			=				output.images
        lowercase_				:List[str]       			=				image[0, -3:, -3:, -1]
        lowercase_				:Union[str, Any]       			=				[
            0.3488_7695,
            0.387_6953,
            0.375,
            0.3442_3828,
            0.358_1543,
            0.3571_7773,
            0.338_3789,
            0.3457_0312,
            0.35_9375,
        ]

        assert image.shape == (1, 512, 512, 3)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2

        # with sega enabled
        # generator = torch.manual_seed(seed)
        generator.manual_seed(SCREAMING_SNAKE_CASE__						)
        lowercase_				:Optional[Any]       			=				pipe(
            [prompt]      ,							generator=SCREAMING_SNAKE_CASE__      ,							guidance_scale=SCREAMING_SNAKE_CASE__      ,							num_inference_steps=50      ,							output_type='''np'''      ,							width=512      ,							height=512      ,							**SCREAMING_SNAKE_CASE__      ,							)

        lowercase_				:Dict       			=				output.images
        lowercase_				:List[Any]       			=				image[0, -3:, -3:, -1]
        lowercase_				:Optional[Any]       			=				[
            0.4228_5156,
            0.3691_4062,
            0.2907_7148,
            0.4204_1016,
            0.4191_8945,
            0.3549_8047,
            0.361_8164,
            0.442_3828,
            0.4311_5234,
        ]

        assert image.shape == (1, 512, 512, 3)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2







from math import floor, sqrt



def 							_A   (						lowerCAmelCase_     :					int			):
     """simple docstring"""

     lowerCAmelCase__		= 0.0
     lowerCAmelCase__		= 1.0
     lowerCAmelCase__		= int(sqrt(lowerCAmelCase_			)			)
     lowerCAmelCase__		= root
     lowerCAmelCase__		= 0
     while integer_part != 2 * root:
          lowerCAmelCase__		= denominator * integer_part - numerator
          lowerCAmelCase__		= (n - numerator**2) / denominator
          lowerCAmelCase__		= int((root + numerator) / denominator			)
          period += 1
     return period



def 							_A   (						lowerCAmelCase_     :					int = 1_0000			):
     """simple docstring"""

     lowerCAmelCase__		= 0
     for i in range(2   ,				n + 1			):
          lowerCAmelCase__		= sqrt(lowerCAmelCase_			)
          if sr - floor(lowerCAmelCase_			) != 0 and continuous_fraction_period(lowerCAmelCase_			) % 2 == 1:
               count_odd_periods += 1
     return count_odd_periods


if __name__ == "__main__":
     print(F"""{solution(int(input().strip()))}""")
