





"""simple docstring"""



import gc
import random
import tempfile
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 		__snake_case (		SCREAMING_SNAKE_CASE__							,							SCREAMING_SNAKE_CASE__							,							unittest.TestCase					):





 """simple docstring"""


 _lowerCamelCase				=					StableDiffusionDiffEditPipeline
 _lowerCamelCase				=					TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""height""", """width""", """image"""} | {"""image_latents"""}
 _lowerCamelCase				=					TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"""image"""} | {"""image_latents"""}
 _lowerCamelCase				=					frozenset(
     []					)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
 _lowerCamelCase				=					frozenset([]					)

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     torch.manual_seed(0  )
     __A   :						Optional[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 ,						attention_head_dim=(2, 4) ,						use_linear_projection=__A ,						)
     __A   :						List[Any]									=					DDIMScheduler(
         beta_start=0.0_0_0_8_5 ,						beta_end=0.0_1_2 ,						beta_schedule='''scaled_linear''' ,						clip_sample=__A ,						set_alpha_to_one=__A ,						)
     __A   :						Optional[int]									=					DDIMInverseScheduler(
         beta_start=0.0_0_0_8_5 ,						beta_end=0.0_1_2 ,						beta_schedule='''scaled_linear''' ,						clip_sample=__A ,						set_alpha_to_zero=__A ,						)
     torch.manual_seed(0  )
     __A   :						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 ,						sample_size=128 ,						)
     torch.manual_seed(0  )
     __A   :						Tuple									=					CLIPTextConfig(
         bos_token_id=0 ,						eos_token_id=2 ,						hidden_size=32 ,						intermediate_size=37 ,						layer_norm_eps=1e-0_5 ,						num_attention_heads=4 ,						num_hidden_layers=5 ,						pad_token_id=1 ,						vocab_size=1000 ,						hidden_act='''gelu''' ,						projection_dim=512 ,						)
     __A   :						List[str]									=					CLIPTextModel(__A  )
     __A   :						Dict									=					CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  )

     __A   :						Optional[int]									=					{
         '''unet''': unet,
         '''scheduler''': scheduler,
         '''inverse_scheduler''': inverse_scheduler,
         '''vae''': vae,
         '''text_encoder''': text_encoder,
         '''tokenizer''': tokenizer,
         '''safety_checker''': None,
         '''feature_extractor''': None,
     }

     return components

 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase=0  ):



     '''simple docstring'''




     __A   :						str									=					floats_tensor((1, 16, 16) ,						rng=random.Random(__A  )  ).to(__A  )
     __A   :						Optional[Any]									=					floats_tensor((1, 2, 4, 16, 16) ,						rng=random.Random(__A  )  ).to(__A  )
     if str(__A  ).startswith('''mps'''  ):
         __A   :						List[Any]									=					torch.manual_seed(__A  )
     else:
         __A   :						int									=					torch.Generator(device=__A  ).manual_seed(__A  )
     __A   :						Tuple									=					{
         '''prompt''': '''a dog and a newt''',
         '''mask_image''': mask,
         '''image_latents''': latents,
         '''generator''': generator,
         '''num_inference_steps''': 2,
         '''inpaint_strength''': 1.0,
         '''guidance_scale''': 6.0,
         '''output_type''': '''numpy''',
     }

     return inputs

 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase=0  ):



     '''simple docstring'''




     __A   :						Dict									=					floats_tensor((1, 3, 32, 32) ,						rng=random.Random(__A  )  ).to(__A  )
     __A   :						Tuple									=					image.cpu().permute(0 ,						2 ,						3 ,						1  )[0]
     __A   :						Dict									=					Image.fromarray(np.uinta(__A  )  ).convert('''RGB'''  )
     if str(__A  ).startswith('''mps'''  ):
         __A   :						Union[str, Any]									=					torch.manual_seed(__A  )
     else:
         __A   :						Tuple									=					torch.Generator(device=__A  ).manual_seed(__A  )
     __A   :						List[Any]									=					{
         '''image''': image,
         '''source_prompt''': '''a cat and a frog''',
         '''target_prompt''': '''a dog and a newt''',
         '''generator''': generator,
         '''num_inference_steps''': 2,
         '''num_maps_per_mask''': 2,
         '''mask_encode_strength''': 1.0,
         '''guidance_scale''': 6.0,
         '''output_type''': '''numpy''',
     }

     return inputs

 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase=0  ):



     '''simple docstring'''




     __A   :						Any									=					floats_tensor((1, 3, 32, 32) ,						rng=random.Random(__A  )  ).to(__A  )
     __A   :						str									=					image.cpu().permute(0 ,						2 ,						3 ,						1  )[0]
     __A   :						Any									=					Image.fromarray(np.uinta(__A  )  ).convert('''RGB'''  )
     if str(__A  ).startswith('''mps'''  ):
         __A   :						Optional[int]									=					torch.manual_seed(__A  )
     else:
         __A   :						List[str]									=					torch.Generator(device=__A  ).manual_seed(__A  )
     __A   :						int									=					{
         '''image''': image,
         '''prompt''': '''a cat and a frog''',
         '''generator''': generator,
         '''num_inference_steps''': 2,
         '''inpaint_strength''': 1.0,
         '''guidance_scale''': 6.0,
         '''decode_latents''': True,
         '''output_type''': '''numpy''',
     }
     return inputs

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     if not hasattr(self.pipeline_class ,						'''_optional_components'''  ):
         return

     __A   :						Dict									=					self.get_dummy_components()
     __A   :						List[Any]									=					self.pipeline_class(**__A  )
     pipe.to(__A  )
     pipe.set_progress_bar_config(disable=__A  )

     # set all optional components to None and update pipeline config accordingly
     for optional_component in pipe._optional_components:
         setattr(__A ,						__A ,						__A  )
     pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}  )

     __A   :						Dict									=					self.get_dummy_inputs(__A  )
     __A   :						Any									=					pipe(**__A  )[0]

     with tempfile.TemporaryDirectory() as tmpdir:
         pipe.save_pretrained(__A  )
         __A   :						int									=					self.pipeline_class.from_pretrained(__A  )
         pipe_loaded.to(__A  )
         pipe_loaded.set_progress_bar_config(disable=__A  )

     for optional_component in pipe._optional_components:
         self.assertTrue(
             getattr(__A ,						__A  ) is None ,						F"""`{optional_component}` did not stay set to None after loading.""" ,						)

     __A   :						int									=					self.get_dummy_inputs(__A  )
     __A   :						Optional[Any]									=					pipe_loaded(**__A  )[0]

     __A   :						Optional[int]									=					np.abs(output - output_loaded  ).max()
     self.assertLess(__A ,						1e-4  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Tuple									=					'''cpu'''

     __A   :						int									=					self.get_dummy_components()
     __A   :						Optional[Any]									=					self.pipeline_class(**__A  )
     pipe.to(__A  )
     pipe.set_progress_bar_config(disable=__A  )

     __A   :						Optional[Any]									=					self.get_dummy_mask_inputs(__A  )
     __A   :						Any									=					pipe.generate_mask(**__A  )
     __A   :						List[Any]									=					mask[0, -3:, -3:]

     self.assertEqual(mask.shape ,						(1, 16, 16)  )
     __A   :						int									=					np.array([0] * 9  )
     __A   :						Dict									=					np.abs(mask_slice.flatten() - expected_slice  ).max()
     self.assertLessEqual(__A ,						1e-3  )
     self.assertEqual(mask[0, -3, -4] ,						0  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[Any]									=					'''cpu'''

     __A   :						str									=					self.get_dummy_components()
     __A   :						Union[str, Any]									=					self.pipeline_class(**__A  )
     pipe.to(__A  )
     pipe.set_progress_bar_config(disable=__A  )

     __A   :						int									=					self.get_dummy_inversion_inputs(__A  )
     __A   :						Any									=					pipe.invert(**__A  ).images
     __A   :						Any									=					image[0, -1, -3:, -3:]

     self.assertEqual(image.shape ,						(2, 32, 32, 3)  )
     __A   :						int									=					np.array(
         [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9] ,						)
     __A   :						str									=					np.abs(image_slice.flatten() - expected_slice  ).max()
     self.assertLessEqual(__A ,						1e-3  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     super().test_inference_batch_single_identical(expected_max_diff=5e-3  )







 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[Any]									=					'''cpu'''

     __A   :						Optional[int]									=					self.get_dummy_components()

     __A   :						Any									=					{'''beta_start''': 0.0_0_0_8_5, '''beta_end''': 0.0_1_2, '''beta_schedule''': '''scaled_linear'''}
     __A   :						Optional[int]									=					DPMSolverMultistepScheduler(**__A  )
     __A   :						int									=					DPMSolverMultistepInverseScheduler(**__A  )

     __A   :						int									=					self.pipeline_class(**__A  )
     pipe.to(__A  )
     pipe.set_progress_bar_config(disable=__A  )

     __A   :						List[str]									=					self.get_dummy_inversion_inputs(__A  )
     __A   :						Dict									=					pipe.invert(**__A  ).images
     __A   :						Dict									=					image[0, -1, -3:, -3:]

     self.assertEqual(image.shape ,						(2, 32, 32, 3)  )
     __A   :						List[str]									=					np.array(
         [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9] ,						)
     __A   :						int									=					np.abs(image_slice.flatten() - expected_slice  ).max()
     self.assertLessEqual(__A ,						1e-3  )






@require_torch_gpu
@slow
class 		__snake_case (		unittest.TestCase					):





 """simple docstring"""


 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()

 @classmethod
 def  UpperCamelCase__(   cls  ):



     '''simple docstring'''




     __A   :						Tuple									=					load_image(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png'''  )

     __A   :						List[Any]									=					raw_image.convert('''RGB'''  ).resize((768, 768)  )

     __A   :						str									=					raw_image

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Tuple									=					torch.manual_seed(0  )

     __A   :						Dict									=					StableDiffusionDiffEditPipeline.from_pretrained(
         '''stabilityai/stable-diffusion-2-1''' ,						safety_checker=__A ,						torch_dtype=torch.floataa  )
     __A   :						List[Any]									=					DDIMScheduler.from_config(pipe.scheduler.config  )
     __A   :						Tuple									=					DDIMInverseScheduler.from_config(pipe.scheduler.config  )
     pipe.enable_model_cpu_offload()
     pipe.set_progress_bar_config(disable=__A  )

     __A   :						Any									=					'''a bowl of fruit'''
     __A   :						List[Any]									=					'''a bowl of pears'''

     __A   :						str									=					pipe.generate_mask(
         image=self.raw_image ,						source_prompt=__A ,						target_prompt=__A ,						generator=__A ,						)

     __A   :						Optional[Any]									=					pipe.invert(
         prompt=__A ,						image=self.raw_image ,						inpaint_strength=0.7 ,						generator=__A  ).latents

     __A   :						int									=					pipe(
         prompt=__A ,						mask_image=__A ,						image_latents=__A ,						generator=__A ,						negative_prompt=__A ,						inpaint_strength=0.7 ,						output_type='''numpy''' ,						).images[0]

     __A   :						List[str]									=					(
         np.array(
             load_image(
                 '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
                 '''/diffedit/pears.png'''  ).resize((768, 768)  )  )
         / 255
     )
     assert np.abs((expected_image - image).max()  ) < 5e-1







 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Union[str, Any]									=					torch.manual_seed(0  )

     __A   :						List[str]									=					StableDiffusionDiffEditPipeline.from_pretrained(
         '''stabilityai/stable-diffusion-2-1''' ,						safety_checker=__A ,						torch_dtype=torch.floataa  )
     __A   :						Optional[int]									=					DPMSolverMultistepScheduler.from_config(pipe.scheduler.config  )
     __A   :						int									=					DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config  )
     pipe.enable_model_cpu_offload()
     pipe.set_progress_bar_config(disable=__A  )

     __A   :						Any									=					'''a bowl of fruit'''
     __A   :						Any									=					'''a bowl of pears'''

     __A   :						Tuple									=					pipe.generate_mask(
         image=self.raw_image ,						source_prompt=__A ,						target_prompt=__A ,						generator=__A ,						)

     __A   :						str									=					pipe.invert(
         prompt=__A ,						image=self.raw_image ,						inpaint_strength=0.7 ,						generator=__A ,						num_inference_steps=25 ,						).latents

     __A   :						Dict									=					pipe(
         prompt=__A ,						mask_image=__A ,						image_latents=__A ,						generator=__A ,						negative_prompt=__A ,						inpaint_strength=0.7 ,						num_inference_steps=25 ,						output_type='''numpy''' ,						).images[0]

     __A   :						str									=					(
         np.array(
             load_image(
                 '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
                 '''/diffedit/pears.png'''  ).resize((768, 768)  )  )
         / 255
     )
     assert np.abs((expected_image - image).max()  ) < 5e-1











"""simple docstring"""



from decimal import Decimal, getcontext
from math import ceil, factorial







def 		__lowercase					(       snake_case_  :  int						)       ->str:



    '''simple docstring'''







    if not isinstance(snake_case_    ,snake_case_						):
        raise TypeError('''Undefined for non-integers'''						)
    elif precision < 1:
        raise ValueError('''Undefined for non-natural numbers'''						)

    __A   :						int									=					precision
    __A   :						Tuple									=					ceil(precision / 14						)
    __A   :						Dict									=					426880 * Decimal(10005						).sqrt()
    __A   :						Optional[Any]									=					1
    __A   :						int									=					13591409
    __A   :						Optional[int]									=					Decimal(snake_case_						)
    for k in range(1    ,snake_case_						):
        __A   :						int									=					factorial(6 * k						) // (factorial(3 * k						) * factorial(snake_case_						) ** 3)
        linear_term += 545140134
        exponential_term *= -262537412640768000
        partial_sum += Decimal(multinomial_term * linear_term						) / exponential_term
    return str(constant_term / partial_sum						)[:-1]


if __name__ == "__main__":
       a_			=      50
       print(f'''The first {n} digits of pi is: {pi(n)}''')




