




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 						lowercase							(   UpperCamelCase__,UpperCamelCase__,UpperCamelCase__,unittest.TestCase		):
     _a							 =						StableDiffusionInpaintPipeline
     _a							 =						TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
     _a							 =						TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
     _a							 =						frozenset(
         []		)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
     _a							 =						frozenset([]		)

     def 					a__	(  self				)						->							Union[str, Any]:
           torch.manual_seed(0				)
           _A							:     List[Any]			=						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=_a		,     )
           _A							:     List[str]			=						PNDMScheduler(skip_prk_steps=_a				)
           torch.manual_seed(0				)
           _A							:     str			=						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							:     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		,     )
           _A							:     Any			=						CLIPTextModel(_a				)
           _A							:     str			=						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""				)

           _A							:     Optional[Any]			=						{
               """unet""": unet,
               """scheduler""": scheduler,
               """vae""": vae,
               """text_encoder""": text_encoder,
               """tokenizer""": tokenizer,
               """safety_checker""": None,
               """feature_extractor""": None,
           }
           return components

     def 					a__	(  self		,     _a		,     _a=0				)						->							str:
           # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
           _A							:     Optional[int]			=						floats_tensor((1, 3, 32, 32)		,     rng=random.Random(_a				)				).to(_a				)
           _A							:     Union[str, Any]			=						image.cpu().permute(0		,     2		,     3		,     1				)[0]
           _A							:     Tuple			=						Image.fromarray(np.uinta(_a				)				).convert("""RGB"""				).resize((64, 64)				)
           _A							:     Dict			=						Image.fromarray(np.uinta(image + 4				)				).convert("""RGB"""				).resize((64, 64)				)
           if str(_a				).startswith("""mps"""				):
                 _A							:     Optional[Any]			=						torch.manual_seed(_a				)
           else:
                 _A							:     Dict			=						torch.Generator(device=_a				).manual_seed(_a				)
           _A							:     Dict			=						{
               """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 					a__	(  self				)						->							List[Any]:
           _A							:     Optional[int]			=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
           _A							:     List[str]			=						self.get_dummy_components()
           _A							:     int			=						StableDiffusionInpaintPipeline(**_a				)
           _A							:     Dict			=						sd_pipe.to(_a				)
           sd_pipe.set_progress_bar_config(disable=_a				)

           _A							:     Optional[Any]			=						self.get_dummy_inputs(_a				)
           _A							:     Optional[Any]			=						sd_pipe(**_a				).images
           _A							:     Union[str, Any]			=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 64, 64, 3)
           _A							:     Dict			=						np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476]				)

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



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







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

     def 					a__	(  self				)						->							Any:
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()

     def 					a__	(  self				)						->							str:
           _A							:     List[Any]			=						load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/sd2-inpaint/init_image.png"""				)
           _A							:     Union[str, Any]			=						load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"""				)
           _A							:     List[Any]			=						load_numpy(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"""
               """/yellow_cat_sitting_on_a_park_bench.npy"""				)

           _A							:     Union[str, Any]			=						"""stabilityai/stable-diffusion-2-inpainting"""
           _A							:     Dict			=						StableDiffusionInpaintPipeline.from_pretrained(_a		,     safety_checker=_a				)
           pipe.to(_a				)
           pipe.set_progress_bar_config(disable=_a				)
           pipe.enable_attention_slicing()

           _A							:     int			=						"""Face of a yellow cat, high resolution, sitting on a park bench"""

           _A							:     List[Any]			=						torch.manual_seed(0				)
           _A							:     str			=						pipe(
               prompt=_a		,     image=_a		,     mask_image=_a		,     generator=_a		,     output_type="""np"""		,     )
           _A							:     Union[str, Any]			=						output.images[0]

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

     def 					a__	(  self				)						->							List[Any]:
           _A							:     List[str]			=						load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/sd2-inpaint/init_image.png"""				)
           _A							:     str			=						load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"""				)
           _A							:     List[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"""				)

           _A							:     Optional[Any]			=						"""stabilityai/stable-diffusion-2-inpainting"""
           _A							:     Tuple			=						StableDiffusionInpaintPipeline.from_pretrained(
               _a		,     torch_dtype=torch.floataa		,     safety_checker=_a		,     )
           pipe.to(_a				)
           pipe.set_progress_bar_config(disable=_a				)
           pipe.enable_attention_slicing()

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

           _A							:     Dict			=						torch.manual_seed(0				)
           _A							:     Optional[int]			=						pipe(
               prompt=_a		,     image=_a		,     mask_image=_a		,     generator=_a		,     output_type="""np"""		,     )
           _A							:     Any			=						output.images[0]

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



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

           _A							:     List[str]			=						load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/sd2-inpaint/init_image.png"""				)
           _A							:     int			=						load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"""				)

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

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

           _A							:     List[Any]			=						torch.manual_seed(0				)
           _A							:     Optional[int]			=						pipe(
               prompt=_a		,     image=_a		,     mask_image=_a		,     generator=_a		,     num_inference_steps=2		,     output_type="""np"""		,     )

           _A							:     Optional[Any]			=						torch.cuda.max_memory_allocated()
           # make sure that less than 2.65 GB is allocated
           assert mem_bytes < 2.65 * 10**9







import unittest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TextaTextGenerationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch
from transformers.utils import is_torch_available

from .test_pipelines_common import ANY


if is_torch_available():
  import torch







@is_pipeline_test
class 						lowercase							(   unittest.TestCase		):
     _a							 =						MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
     _a							 =						TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

     def 					a__	(  self		,     _a		,     _a		,     _a				)						->							int:
           _A							:     str			=						TextaTextGenerationPipeline(model=_a		,     tokenizer=_a				)
           return generator, ["Something to write", "Something else"]

     def 					a__	(  self		,     _a		,     _a				)						->							Dict:
           _A							:     Any			=						generator("""Something there"""				)
           self.assertEqual(_a		,     [{"""generated_text""": ANY(_a				)}]				)
           # These are encoder decoder, they don't just append to incoming string
           self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there"""				)				)

           _A							:     List[Any]			=						generator(["""This is great !""", """Something else"""]		,     num_return_sequences=2		,     do_sample=_a				)
           self.assertEqual(
               _a		,     [
                   [{"""generated_text""": ANY(_a				)}, {"""generated_text""": ANY(_a				)}],
                   [{"""generated_text""": ANY(_a				)}, {"""generated_text""": ANY(_a				)}],
               ]		,     )

           _A							:     Optional[int]			=						generator(
               ["""This is great !""", """Something else"""]		,     num_return_sequences=2		,     batch_size=2		,     do_sample=_a				)
           self.assertEqual(
               _a		,     [
                   [{"""generated_text""": ANY(_a				)}, {"""generated_text""": ANY(_a				)}],
                   [{"""generated_text""": ANY(_a				)}, {"""generated_text""": ANY(_a				)}],
               ]		,     )

           with self.assertRaises(_a				):
                 generator(4				)

     @require_torch
     def 					a__	(  self				)						->							List[str]:
           _A							:     Any			=						pipeline("""text2text-generation"""		,     model="""patrickvonplaten/t5-tiny-random"""		,     framework="""pt"""				)
           # do_sample=False necessary for reproducibility
           _A							:     Dict			=						generator("""Something there"""		,     do_sample=_a				)
           self.assertEqual(_a		,     [{"""generated_text""": """"""}]				)

           _A							:     Any			=						3
           _A							:     Any			=						generator(
               """Something there"""		,     num_return_sequences=_a		,     num_beams=_a		,     )
           _A							:     Optional[int]			=						[
               {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide Beide"""},
               {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide"""},
               {"""generated_text""": """"""},
           ]
           self.assertEqual(_a		,     _a				)

           _A							:     Dict			=						generator("""This is a test"""		,     do_sample=_a		,     num_return_sequences=2		,     return_tensors=_a				)
           self.assertEqual(
               _a		,     [
                   {"""generated_token_ids""": ANY(torch.Tensor				)},
                   {"""generated_token_ids""": ANY(torch.Tensor				)},
               ]		,     )
           _A							:     Dict			=						generator.model.config.eos_token_id
           _A							:     List[str]			=						"""<pad>"""
           _A							:     Dict			=						generator(
               ["""This is a test""", """This is a second test"""]		,     do_sample=_a		,     num_return_sequences=2		,     batch_size=2		,     return_tensors=_a		,     )
           self.assertEqual(
               _a		,     [
                   [
                       {"""generated_token_ids""": ANY(torch.Tensor				)},
                       {"""generated_token_ids""": ANY(torch.Tensor				)},
                   ],
                   [
                       {"""generated_token_ids""": ANY(torch.Tensor				)},
                       {"""generated_token_ids""": ANY(torch.Tensor				)},
                   ],
               ]		,     )



     @require_tf
     def 					a__	(  self				)						->							int:
           _A							:     Optional[Any]			=						pipeline("""text2text-generation"""		,     model="""patrickvonplaten/t5-tiny-random"""		,     framework="""tf"""				)
           # do_sample=False necessary for reproducibility
           _A							:     str			=						generator("""Something there"""		,     do_sample=_a				)
           self.assertEqual(_a		,     [{"""generated_text""": """"""}]				)

