



'''simple docstring'''





import os
import tempfile
import unittest
import uuid
from pathlib import Path

from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision
from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText
from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available


if is_torch_available():
    import torch

if is_soundfile_availble():
    import soundfile as sf

if is_vision_available():
    from PIL import Image





def   a_   (		_UpperCAmelCase    :      List[str]=""				)    ->  str:
      __snake_case :   Union[str, Any]													=    tempfile.mkdtemp()
      return os.path.join(_UpperCAmelCase ,str(uuid.uuida()				) + suffix				)



@require_soundfile
@require_torch
class  snake_case__						(    unittest.TestCase				):
 def A_   (   self						:							Optional[Any]  )      ->   Optional[int]:







       '''simple docstring'''
       __snake_case :   List[str]													=    torch.rand(12      ,     dtype=torch.floataa  ) - 0.5
       __snake_case :   Dict													=    AgentAudio(__a  )
       __snake_case :   Optional[int]													=    str(agent_type.to_string()  )

       # Ensure that the tensor and the agent_type's tensor are the same
       self.assertTrue(torch.allclose(__a      ,     agent_type.to_raw()      ,     atol=1e-4  )  )

       del agent_type

       # Ensure the path remains even after the object deletion
       self.assertTrue(os.path.exists(__a  )  )

       # Ensure that the file contains the same value as the original tensor
       __snake_case							,     __snake_case :   Optional[Any]													=    sf.read(__a  )
       self.assertTrue(torch.allclose(__a      ,     torch.tensor(__a  )      ,     atol=1e-4  )  )





 def A_   (   self						:							Any  )      ->   Optional[int]:







       '''simple docstring'''
       __snake_case :   Union[str, Any]													=    torch.rand(12      ,     dtype=torch.floataa  ) - 0.5
       __snake_case :   List[Any]													=    get_new_path(suffix='.wav'  )
       sf.write(__a      ,     __a      ,     16000  )

       __snake_case :   List[Any]													=    AgentAudio(__a  )

       self.assertTrue(torch.allclose(__a      ,     agent_type.to_raw()      ,     atol=1e-4  )  )
       self.assertEqual(agent_type.to_string()      ,     __a  )



@require_vision
@require_torch
class  snake_case__						(    unittest.TestCase				):
 def A_   (   self						:							int  )      ->   Union[str, Any]:







       '''simple docstring'''
       __snake_case :   Union[str, Any]													=    torch.randint(0      ,     256      ,     (64, 64, 3)  )
       __snake_case :   Optional[int]													=    AgentImage(__a  )
       __snake_case :   Any													=    str(agent_type.to_string()  )

       # Ensure that the tensor and the agent_type's tensor are the same
       self.assertTrue(torch.allclose(__a      ,     agent_type._tensor      ,     atol=1e-4  )  )

       self.assertIsInstance(agent_type.to_raw()      ,     Image.Image  )

       # Ensure the path remains even after the object deletion
       del agent_type
       self.assertTrue(os.path.exists(__a  )  )
 def A_   (   self						:							Optional[Any]  )      ->   List[str]:







       '''simple docstring'''
       __snake_case :   Tuple													=    Path(get_tests_dir('fixtures/tests_samples/COCO'  )  ) / '000000039769.png'
       __snake_case :   Dict													=    Image.open(__a  )
       __snake_case :   Optional[int]													=    AgentImage(__a  )

       self.assertTrue(path.samefile(agent_type.to_string()  )  )
       self.assertTrue(image == agent_type.to_raw()  )

       # Ensure the path remains even after the object deletion
       del agent_type
       self.assertTrue(os.path.exists(__a  )  )





 def A_   (   self						:							Dict  )      ->   Optional[Any]:







       '''simple docstring'''
       __snake_case :   List[Any]													=    Path(get_tests_dir('fixtures/tests_samples/COCO'  )  ) / '000000039769.png'
       __snake_case :   Union[str, Any]													=    Image.open(__a  )
       __snake_case :   Union[str, Any]													=    AgentImage(__a  )

       self.assertFalse(path.samefile(agent_type.to_string()  )  )
       self.assertTrue(image == agent_type.to_raw()  )

       # Ensure the path remains even after the object deletion
       del agent_type
       self.assertTrue(os.path.exists(__a  )  )



class  snake_case__						(    unittest.TestCase				):
 def A_   (   self						:							Tuple  )      ->   int:







       '''simple docstring'''
       __snake_case :   Tuple													=    'Hey!'
       __snake_case :   Union[str, Any]													=    AgentText(__a  )

       self.assertEqual(__a      ,     agent_type.to_string()  )
       self.assertEqual(__a      ,     agent_type.to_raw()  )
       self.assertEqual(__a      ,     __a  )








'''simple docstring'''





import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()



class  snake_case__						(    SCREAMING_SNAKE_CASE_  ,     unittest.TestCase				):
 A__				= KandinskyInpaintPipeline
 A__				= ['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''']
 A__				= [
     '''prompt''',
     '''negative_prompt''',
     '''image_embeds''',
     '''negative_image_embeds''',
     '''image''',
     '''mask_image''',
 ]
 A__				= [
     '''generator''',
     '''height''',
     '''width''',
     '''latents''',
     '''guidance_scale''',
     '''negative_prompt''',
     '''num_inference_steps''',
     '''return_dict''',
     '''guidance_scale''',
     '''num_images_per_prompt''',
     '''output_type''',
     '''return_dict''',
 ]
 A__				= False
 @property
 def A_   (   self						:							Dict  )      ->   Union[str, Any]:







       '''simple docstring'''
       return 32
 @property
 def A_   (   self						:							Optional[int]  )      ->   Tuple:







       '''simple docstring'''
       return 32
 @property
 def A_   (   self						:							Dict  )      ->   str:







       '''simple docstring'''
       return self.time_input_dim
 @property
 def A_   (   self						:							Dict  )      ->   Any:







       '''simple docstring'''
       return self.time_input_dim * 4
 @property
 def A_   (   self						:							List[Any]  )      ->   List[str]:







       '''simple docstring'''
       return 100
 @property
 def A_   (   self						:							int  )      ->   Union[str, Any]:







       '''simple docstring'''
       __snake_case :   List[str]													=    XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base'  )
       return tokenizer
 @property
 def A_   (   self						:							Tuple  )      ->   str:







       '''simple docstring'''
       torch.manual_seed(0  )
       __snake_case :   str													=    MCLIPConfig(
           numDims=self.cross_attention_dim      ,     transformerDimensions=self.text_embedder_hidden_size      ,     hidden_size=self.text_embedder_hidden_size      ,     intermediate_size=37      ,     num_attention_heads=4      ,     num_hidden_layers=5      ,     vocab_size=1005      ,     )

       __snake_case :   List[Any]													=    MultilingualCLIP(__a  )
       __snake_case :   List[str]													=    text_encoder.eval()

       return text_encoder
 @property
 def A_   (   self						:							Dict  )      ->   List[str]:







       '''simple docstring'''
       torch.manual_seed(0  )

       __snake_case :   Tuple													=    {
           'in_channels': 9,
           # Out channels is double in channels because predicts mean and variance
           'out_channels': 8,
           'addition_embed_type': 'text_image',
           'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'),
           'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'),
           'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn',
           'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2),
           'layers_per_block': 1,
           'encoder_hid_dim': self.text_embedder_hidden_size,
           'encoder_hid_dim_type': 'text_image_proj',
           'cross_attention_dim': self.cross_attention_dim,
           'attention_head_dim': 4,
           'resnet_time_scale_shift': 'scale_shift',
           'class_embed_type': None,
       }

       __snake_case :   Any													=    UNetaDConditionModel(**__a  )
       return model
 @property
 def A_   (   self						:							List[str]  )      ->   List[Any]:







       '''simple docstring'''
       return {
           "block_out_channels": [32, 64],
           "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
           "in_channels": 3,
           "latent_channels": 4,
           "layers_per_block": 1,
           "norm_num_groups": 8,
           "norm_type": "spatial",
           "num_vq_embeddings": 12,
           "out_channels": 3,
           "up_block_types": [
               "AttnUpDecoderBlock2D",
               "UpDecoderBlock2D",
           ],
           "vq_embed_dim": 4,
       }
 @property
 def A_   (   self						:							int  )      ->   List[str]:







       '''simple docstring'''
       torch.manual_seed(0  )
       __snake_case :   Optional[int]													=    VQModel(**self.dummy_movq_kwargs  )
       return model
 def A_   (   self						:							Dict  )      ->   Tuple:







       '''simple docstring'''
       __snake_case :   Tuple													=    self.dummy_text_encoder
       __snake_case :   str													=    self.dummy_tokenizer
       __snake_case :   Any													=    self.dummy_unet
       __snake_case :   Optional[Any]													=    self.dummy_movq

       __snake_case :   Optional[Any]													=    DDIMScheduler(
           num_train_timesteps=1000      ,     beta_schedule='linear'      ,     beta_start=0.0_0_0_8_5      ,     beta_end=0.0_1_2      ,     clip_sample=__a      ,     set_alpha_to_one=__a      ,     steps_offset=1      ,     prediction_type='epsilon'      ,     thresholding=__a      ,     )

       __snake_case :   List[str]													=    {
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'unet': unet,
           'scheduler': scheduler,
           'movq': movq,
       }

       return components
 def A_   (   self						:							List[str]      ,     __a						:							Dict      ,     __a						:							int=0  )      ->   Optional[Any]:







       '''simple docstring'''
       __snake_case :   int													=    floats_tensor((1, self.cross_attention_dim)      ,     rng=random.Random(__a  )  ).to(__a  )
       __snake_case :   str													=    floats_tensor((1, self.cross_attention_dim)      ,     rng=random.Random(seed + 1  )  ).to(__a  )
       # create init_image
       __snake_case :   Any													=    floats_tensor((1, 3, 64, 64)      ,     rng=random.Random(__a  )  ).to(__a  )
       __snake_case :   Optional[int]													=    image.cpu().permute(0      ,     2      ,     3      ,     1  )[0]
       __snake_case :   List[str]													=    Image.fromarray(np.uinta(__a  )  ).convert('RGB'  ).resize((256, 256)  )
       # create mask
       __snake_case :   Optional[int]													=    np.ones((64, 64)      ,     dtype=np.floataa  )
       __snake_case :   List[Any]													=    0

       if str(__a  ).startswith('mps'  ):
             __snake_case :   Any													=    torch.manual_seed(__a  )
       else:
             __snake_case :   Optional[int]													=    torch.Generator(device=__a  ).manual_seed(__a  )
       __snake_case :   int													=    {
           'prompt': 'horse',
           'image': init_image,
           'mask_image': mask,
           'image_embeds': image_embeds,
           'negative_image_embeds': negative_image_embeds,
           'generator': generator,
           'height': 64,
           'width': 64,
           'num_inference_steps': 2,
           'guidance_scale': 4.0,
           'output_type': 'np',
       }
       return inputs
 def A_   (   self						:							Any  )      ->   int:







       '''simple docstring'''
       __snake_case :   List[str]													=    'cpu'

       __snake_case :   Tuple													=    self.get_dummy_components()

       __snake_case :   Optional[int]													=    self.pipeline_class(**__a  )
       __snake_case :   Union[str, Any]													=    pipe.to(__a  )

       pipe.set_progress_bar_config(disable=__a  )

       __snake_case :   Optional[Any]													=    pipe(**self.get_dummy_inputs(__a  )  )
       __snake_case :   Dict													=    output.images

       __snake_case :   Union[str, Any]													=    pipe(
           **self.get_dummy_inputs(__a  )      ,     return_dict=__a      ,     )[0]

       __snake_case :   int													=    image[0, -3:, -3:, -1]
       __snake_case :   Optional[int]													=    image_from_tuple[0, -3:, -3:, -1]

       print(f'''image.shape {image.shape}'''  )

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

       __snake_case :   List[Any]													=    np.array(
           [0.8_3_2_6_9_1_9, 0.7_3_7_9_0_4_6_7, 0.2_0_9_1_8_5_8_1, 0.9_3_0_9_6_1_2, 0.5_5_1_1_7_9_1, 0.4_3_7_1_3_3_2_8, 0.5_5_1_3_3_2_1, 0.4_9_9_2_2_9_3_4, 0.5_9_4_9_7_7_8_6]  )

       assert (
           np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2
       ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
       assert (
           np.abs(image_from_tuple_slice.flatten() - expected_slice  ).max() < 1e-2
       ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''





 def A_   (   self						:							List[Any]  )      ->   List[str]:







       '''simple docstring'''
       super().test_inference_batch_single_identical(expected_max_diff=3e-3  )



@slow
@require_torch_gpu
class  snake_case__						(    unittest.TestCase				):
 def A_   (   self						:							Dict  )      ->   List[str]:







       '''simple docstring'''
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()





 def A_   (   self						:							Optional[int]  )      ->   List[Any]:







       '''simple docstring'''
       __snake_case :   Union[str, Any]													=    load_numpy(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
           '/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy'  )

       __snake_case :   Tuple													=    load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png'  )
       __snake_case :   Tuple													=    np.ones((768, 768)      ,     dtype=np.floataa  )
       __snake_case :   Tuple													=    0

       __snake_case :   Tuple													=    'a hat'

       __snake_case :   Optional[Any]													=    KandinskyPriorPipeline.from_pretrained(
           'kandinsky-community/kandinsky-2-1-prior'      ,     torch_dtype=torch.floataa  )
       pipe_prior.to(__a  )

       __snake_case :   int													=    KandinskyInpaintPipeline.from_pretrained(
           'kandinsky-community/kandinsky-2-1-inpaint'      ,     torch_dtype=torch.floataa  )
       __snake_case :   Optional[Any]													=    pipeline.to(__a  )
       pipeline.set_progress_bar_config(disable=__a  )

       __snake_case :   Any													=    torch.Generator(device='cpu'  ).manual_seed(0  )
       __snake_case							,     __snake_case :   Union[str, Any]													=    pipe_prior(
           __a      ,     generator=__a      ,     num_inference_steps=5      ,     negative_prompt=''      ,     ).to_tuple()

       __snake_case :   List[str]													=    pipeline(
           __a      ,     image=__a      ,     mask_image=__a      ,     image_embeds=__a      ,     negative_image_embeds=__a      ,     generator=__a      ,     num_inference_steps=100      ,     height=768      ,     width=768      ,     output_type='np'      ,     )

       __snake_case :   int													=    output.images[0]

       assert image.shape == (768, 768, 3)

       assert_mean_pixel_difference(__a      ,     __a  )



