

'''simple docstring'''



import gc
import random
import unittest

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

from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow

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


enable_full_determinism()



class 			a       (	_a			,						_a			,						_a			,						unittest.TestCase ):


     """simple docstring"""






     SCREAMING_SNAKE_CASE :				List[str]							     =     StableDiffusionInpaintPipeline
     SCREAMING_SNAKE_CASE :				Any							     =     TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
     SCREAMING_SNAKE_CASE :				List[str]							     =     TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
     SCREAMING_SNAKE_CASE :				List[Any]							     =     frozenset(
         [] )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
     SCREAMING_SNAKE_CASE :				Dict							     =     frozenset([] )

     def 				lowerCamelCase__				(       self  :	str    )		->							List[str]:
          torch.manual_seed(0    )
          __UpperCAmelCase			:				str													=    UNetaDConditionModel(
              block_out_channels=(32, 64)							,				layers_per_block=2							,				sample_size=32							,				in_channels=9							,				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=snake_case							,				)
          __UpperCAmelCase			:				Dict													=    PNDMScheduler(skip_prk_steps=snake_case    )
          torch.manual_seed(0    )
          __UpperCAmelCase			:				int													=    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    )
          __UpperCAmelCase			:				Union[str, 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							,				hidden_act='''gelu'''							,				projection_dim=512							,				)
          __UpperCAmelCase			:				Optional[int]													=    CLIPTextModel(snake_case    )
          __UpperCAmelCase			:				List[Any]													=    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    )

          __UpperCAmelCase			:				Tuple													=    {
              'unet': unet,
              'scheduler': scheduler,
              'vae': vae,
              'text_encoder': text_encoder,
              'tokenizer': tokenizer,
              'safety_checker': None,
              'feature_extractor': None,
          }
          return components

     def 				lowerCamelCase__				(       self  :	Optional[Any]							,				snake_case  :	Dict							,				snake_case  :	Union[str, Any]=0    )		->							List[Any]:
          __UpperCAmelCase			:				Any													=    floats_tensor((1, 3, 32, 32)							,				rng=random.Random(snake_case    )    ).to(snake_case    )
          __UpperCAmelCase			:				Optional[int]													=    image.cpu().permute(0							,				2							,				3							,				1    )[0]
          __UpperCAmelCase			:				Dict													=    Image.fromarray(np.uinta(snake_case    )    ).convert('''RGB'''    ).resize((64, 64)    )
          __UpperCAmelCase			:				Optional[Any]													=    Image.fromarray(np.uinta(image + 4    )    ).convert('''RGB'''    ).resize((64, 64)    )
          if str(snake_case    ).startswith('''mps'''    ):
               __UpperCAmelCase			:				Optional[int]													=    torch.manual_seed(snake_case    )
          else:
               __UpperCAmelCase			:				Union[str, Any]													=    torch.Generator(device=snake_case    ).manual_seed(snake_case    )
          __UpperCAmelCase			:				Optional[int]													=    {
              'prompt': 'A painting of a squirrel eating a burger',
              'image': init_image,
              'mask_image': mask_image,
              'generator': generator,
              'num_inference_steps': 2,
              'guidance_scale': 6.0,
              'output_type': 'numpy',
          }
          return inputs

     def 				lowerCamelCase__				(       self  :	Optional[int]    )		->							List[str]:
          __UpperCAmelCase			:				Tuple													=    'cpu'  # ensure determinism for the device-dependent torch.Generator
          __UpperCAmelCase			:				Optional[Any]													=    self.get_dummy_components()
          __UpperCAmelCase			:				List[str]													=    StableDiffusionInpaintPipeline(**snake_case    )
          __UpperCAmelCase			:				Tuple													=    sd_pipe.to(snake_case    )
          sd_pipe.set_progress_bar_config(disable=snake_case    )

          __UpperCAmelCase			:				Optional[int]													=    self.get_dummy_inputs(snake_case    )
          __UpperCAmelCase			:				Tuple													=    sd_pipe(**snake_case    ).images
          __UpperCAmelCase			:				Optional[Any]													=    image[0, -3:, -3:, -1]

          assert image.shape == (1, 64, 64, 3)
          __UpperCAmelCase			:				Union[str, Any]													=    np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476]    )

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






     def 				lowerCamelCase__				(       self  :	List[str]    )		->							List[str]:
          super().test_inference_batch_single_identical(expected_max_diff=3E-3    )



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


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	Dict    )		->							Optional[int]:
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()

     def 				lowerCamelCase__				(       self  :	List[Any]    )		->							Optional[Any]:
          __UpperCAmelCase			:				List[str]													=    load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/sd2-inpaint/init_image.png'''    )
          __UpperCAmelCase			:				List[str]													=    load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''    )
          __UpperCAmelCase			:				List[str]													=    load_numpy(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
              '''/yellow_cat_sitting_on_a_park_bench.npy'''    )

          __UpperCAmelCase			:				List[str]													=    'stabilityai/stable-diffusion-2-inpainting'
          __UpperCAmelCase			:				str													=    StableDiffusionInpaintPipeline.from_pretrained(snake_case							,				safety_checker=snake_case    )
          pipe.to(snake_case    )
          pipe.set_progress_bar_config(disable=snake_case    )
          pipe.enable_attention_slicing()

          __UpperCAmelCase			:				Dict													=    'Face of a yellow cat, high resolution, sitting on a park bench'

          __UpperCAmelCase			:				Tuple													=    torch.manual_seed(0    )
          __UpperCAmelCase			:				List[str]													=    pipe(
              prompt=snake_case							,				image=snake_case							,				mask_image=snake_case							,				generator=snake_case							,				output_type='''np'''							,				)
          __UpperCAmelCase			:				List[str]													=    output.images[0]

          assert image.shape == (512, 512, 3)
          assert np.abs(expected_image - image    ).max() < 9E-3

     def 				lowerCamelCase__				(       self  :	Dict    )		->							Optional[Any]:
          __UpperCAmelCase			:				str													=    load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/sd2-inpaint/init_image.png'''    )
          __UpperCAmelCase			:				Union[str, Any]													=    load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''    )
          __UpperCAmelCase			:				str													=    load_numpy(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
              '''/yellow_cat_sitting_on_a_park_bench_fp16.npy'''    )

          __UpperCAmelCase			:				Tuple													=    'stabilityai/stable-diffusion-2-inpainting'
          __UpperCAmelCase			:				Tuple													=    StableDiffusionInpaintPipeline.from_pretrained(
              snake_case							,				torch_dtype=torch.floataa							,				safety_checker=snake_case							,				)
          pipe.to(snake_case    )
          pipe.set_progress_bar_config(disable=snake_case    )
          pipe.enable_attention_slicing()

          __UpperCAmelCase			:				Optional[int]													=    'Face of a yellow cat, high resolution, sitting on a park bench'

          __UpperCAmelCase			:				int													=    torch.manual_seed(0    )
          __UpperCAmelCase			:				List[Any]													=    pipe(
              prompt=snake_case							,				image=snake_case							,				mask_image=snake_case							,				generator=snake_case							,				output_type='''np'''							,				)
          __UpperCAmelCase			:				Tuple													=    output.images[0]

          assert image.shape == (512, 512, 3)
          assert np.abs(expected_image - image    ).max() < 5E-1






     def 				lowerCamelCase__				(       self  :	Any    )		->							List[str]:
          torch.cuda.empty_cache()
          torch.cuda.reset_max_memory_allocated()
          torch.cuda.reset_peak_memory_stats()

          __UpperCAmelCase			:				List[Any]													=    load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/sd2-inpaint/init_image.png'''    )
          __UpperCAmelCase			:				List[Any]													=    load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''    )

          __UpperCAmelCase			:				Tuple													=    'stabilityai/stable-diffusion-2-inpainting'
          __UpperCAmelCase			:				List[str]													=    PNDMScheduler.from_pretrained(snake_case							,				subfolder='''scheduler'''    )
          __UpperCAmelCase			:				List[Any]													=    StableDiffusionInpaintPipeline.from_pretrained(
              snake_case							,				safety_checker=snake_case							,				scheduler=snake_case							,				torch_dtype=torch.floataa							,				)
          pipe.to(snake_case    )
          pipe.set_progress_bar_config(disable=snake_case    )
          pipe.enable_attention_slicing(1    )
          pipe.enable_sequential_cpu_offload()

          __UpperCAmelCase			:				List[str]													=    'Face of a yellow cat, high resolution, sitting on a park bench'

          __UpperCAmelCase			:				List[str]													=    torch.manual_seed(0    )
          __UpperCAmelCase			:				Union[str, Any]													=    pipe(
              prompt=snake_case							,				image=snake_case							,				mask_image=snake_case							,				generator=snake_case							,				num_inference_steps=2							,				output_type='''np'''							,				)

          __UpperCAmelCase			:				str													=    torch.cuda.max_memory_allocated()
          # make sure that less than 2.65 GB is allocated
          assert mem_bytes < 2.65 * 10**9



'''simple docstring'''



import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow


if is_tf_available():
      import tensorflow as tf

if is_tensorflow_text_available():
      from transformers.models.bert import TFBertTokenizer


__UpperCAmelCase    :Optional[int]				       =     ["bert-base-uncased", "bert-base-cased"]
__UpperCAmelCase    :str				       =     "hf-internal-testing/tiny-bert-tf-only"

if is_tf_available():



      class 			a       (	tf.keras.Model ):


           """simple docstring"""






           def __init__(       self  :	List[str]							,				snake_case  :	List[str]    )		->							str:
                super().__init__()
                __UpperCAmelCase			:				List[str]													=    tokenizer
                __UpperCAmelCase			:				List[Any]													=    AutoConfig.from_pretrained(snake_case    )
                __UpperCAmelCase			:				int													=    TFAutoModel.from_config(snake_case    )






           def 				lowerCamelCase__				(       self  :	List[Any]							,				snake_case  :	Optional[int]    )		->							Optional[Any]:
                __UpperCAmelCase			:				List[Any]													=    self.tokenizer(snake_case    )
                __UpperCAmelCase			:				Optional[Any]													=    self.bert(**snake_case    )
                return out["pooler_output"]



@require_tf
@require_tensorflow_text
class 			a       (	unittest.TestCase ):


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	Optional[int]    )		->							List[str]:
          super().setUp()

          __UpperCAmelCase			:				Tuple													=    [
              BertTokenizer.from_pretrained(snake_case    ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
          ]  # repeat for when fast_bert_tokenizer=false
          __UpperCAmelCase			:				Any													=    [TFBertTokenizer.from_pretrained(snake_case    ) for checkpoint in TOKENIZER_CHECKPOINTS] + [
              TFBertTokenizer.from_pretrained(snake_case							,				use_fast_bert_tokenizer=snake_case    )
              for checkpoint in TOKENIZER_CHECKPOINTS
          ]
          assert len(self.tokenizers    ) == len(self.tf_tokenizers    )

          __UpperCAmelCase			:				Optional[int]													=    [
              '''This is a straightforward English test sentence.''',
              '''This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.''',
              '''Now we\'re going to add some Chinese: 一 二 三 一二三''',
              '''And some much more rare Chinese: 齉 堃 齉堃''',
              '''Je vais aussi écrire en français pour tester les accents''',
              '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',
          ]
          __UpperCAmelCase			:				Optional[int]													=    list(zip(self.test_sentences							,				self.test_sentences[::-1]    )    )

     def 				lowerCamelCase__				(       self  :	Optional[int]    )		->							Optional[Any]:
          for tokenizer, tf_tokenizer in zip(self.tokenizers							,				self.tf_tokenizers    ):
               for test_inputs in (self.test_sentences, self.paired_sentences):
                    __UpperCAmelCase			:				Any													=    tokenizer(snake_case							,				return_tensors='''tf'''							,				padding='''longest'''    )
                    __UpperCAmelCase			:				Optional[int]													=    tf_tokenizer(snake_case    )

                    for key in python_outputs.keys():
                         self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape    )    )
                         self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key]							,				tf.intaa    ) == tf_outputs[key]    )    )

     @slow
     def 				lowerCamelCase__				(       self  :	List[Any]    )		->							str:
          for tf_tokenizer in self.tf_tokenizers:
               __UpperCAmelCase			:				Any													=    tf_tokenizer(self.paired_sentences    )
               __UpperCAmelCase			:				Union[str, Any]													=    tf_tokenizer(
                   text=[sentence[0] for sentence in self.paired_sentences]							,				text_pair=[sentence[1] for sentence in self.paired_sentences]							,				)
               for key in merged_outputs.keys():
                    self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key]							,				tf.intaa    ) == separated_outputs[key]    )    )

     @slow
     def 				lowerCamelCase__				(       self  :	str    )		->							Union[str, Any]:
          for tf_tokenizer in self.tf_tokenizers:
               __UpperCAmelCase			:				Optional[int]													=    tf.function(snake_case    )
               for test_inputs in (self.test_sentences, self.paired_sentences):
                    __UpperCAmelCase			:				int													=    tf.constant(snake_case    )
                    __UpperCAmelCase			:				Tuple													=    compiled_tokenizer(snake_case    )
                    __UpperCAmelCase			:				Optional[int]													=    tf_tokenizer(snake_case    )

                    for key in eager_outputs.keys():
                         self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]    )    )






     @slow
     def 				lowerCamelCase__				(       self  :	str    )		->							str:
          for tf_tokenizer in self.tf_tokenizers:
               __UpperCAmelCase			:				List[Any]													=    ModelToSave(tokenizer=snake_case    )
               __UpperCAmelCase			:				Union[str, Any]													=    tf.convert_to_tensor(self.test_sentences    )
               __UpperCAmelCase			:				Tuple													=    model(snake_case    )  # Build model with some sample inputs
               with TemporaryDirectory() as tempdir:
                    __UpperCAmelCase			:				Any													=    Path(snake_case    ) / '''saved.model'''
                    model.save(snake_case    )
                    __UpperCAmelCase			:				str													=    tf.keras.models.load_model(snake_case    )
               __UpperCAmelCase			:				Optional[int]													=    loaded_model(snake_case    )
               # We may see small differences because the loaded model is compiled, so we need an epsilon for the test
               self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output    )    )							,				1E-5    )