
'''simple docstring'''

import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class      a_     (__A							,	unittest.TestCase			):
       __lowerCAmelCase			: Optional[int]			=					LDMTextToImagePipeline
       __lowerCAmelCase			: int			=					TEXT_TO_IMAGE_PARAMS - {
           "negative_prompt",
           "negative_prompt_embeds",
           "cross_attention_kwargs",
           "prompt_embeds",
       }
       __lowerCAmelCase			: Optional[Any]			=					PipelineTesterMixin.required_optional_params - {
           "num_images_per_prompt",
           "callback",
           "callback_steps",
       }
       __lowerCAmelCase			: Any			=					TEXT_TO_IMAGE_BATCH_PARAMS
       __lowerCAmelCase			: str			=					False




       def 							__UpperCamelCase				(   self     ):
         torch.manual_seed(0     )
         _lowerCAmelCase				:     List[Any]       =    UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)      ,      layers_per_block=2      ,      sample_size=3_2      ,      in_channels=4      ,      out_channels=4      ,      down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")      ,      up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")      ,      cross_attention_dim=3_2      ,      )
         _lowerCAmelCase				:     List[str]       =    DDIMScheduler(
             beta_start=0.0_0085      ,      beta_end=0.012      ,      beta_schedule="""scaled_linear"""      ,      clip_sample=lowercase_      ,      set_alpha_to_one=lowercase_      ,      )
         torch.manual_seed(0     )
         _lowerCAmelCase				:     str       =    AutoencoderKL(
             block_out_channels=(3_2, 6_4)      ,      in_channels=3      ,      out_channels=3      ,      down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""")      ,      up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""")      ,      latent_channels=4      ,      )
         torch.manual_seed(0     )
         _lowerCAmelCase				:     Optional[Any]       =    CLIPTextConfig(
             bos_token_id=0      ,      eos_token_id=2      ,      hidden_size=3_2      ,      intermediate_size=3_7      ,      layer_norm_eps=1E-05      ,      num_attention_heads=4      ,      num_hidden_layers=5      ,      pad_token_id=1      ,      vocab_size=1_0_0_0      ,      )
         _lowerCAmelCase				:     Optional[int]       =    CLIPTextModel(lowercase_     )
         _lowerCAmelCase				:     Union[str, Any]       =    CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""     )

         _lowerCAmelCase				:     List[Any]       =    {
             "unet": unet,
             "scheduler": scheduler,
             "vqvae": vae,
             "bert": text_encoder,
             "tokenizer": tokenizer,
         }
         return components




       def 							__UpperCamelCase				(   self      ,      snake_case_      ,      snake_case_=0     ):
         if str(lowercase_     ).startswith("""mps"""     ):
           _lowerCAmelCase				:     int       =    torch.manual_seed(lowercase_     )
         else:
           _lowerCAmelCase				:     List[str]       =    torch.Generator(device=lowercase_     ).manual_seed(lowercase_     )
         _lowerCAmelCase				:     List[str]       =    {
             "prompt": "A painting of a squirrel eating a burger",
             "generator": generator,
             "num_inference_steps": 2,
             "guidance_scale": 6.0,
             "output_type": "numpy",
         }
         return inputs







       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     List[Any]       =    "cpu"  # ensure determinism for the device-dependent torch.Generator

         _lowerCAmelCase				:     str       =    self.get_dummy_components()
         _lowerCAmelCase				:     Any       =    LDMTextToImagePipeline(**lowercase_     )
         pipe.to(lowercase_     )
         pipe.set_progress_bar_config(disable=lowercase_     )

         _lowerCAmelCase				:     str       =    self.get_dummy_inputs(lowercase_     )
         _lowerCAmelCase				:     Union[str, Any]       =    pipe(**lowercase_     ).images
         _lowerCAmelCase				:     List[Any]       =    image[0, -3:, -3:, -1]

         assert image.shape == (1, 1_6, 1_6, 3)
         _lowerCAmelCase				:     int       =    np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014]     )

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



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




       def 							__UpperCamelCase				(   self     ):
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()




       def 							__UpperCamelCase				(   self      ,      snake_case_      ,      snake_case_=torch.floataa      ,      snake_case_=0     ):
         _lowerCAmelCase				:     Dict       =    torch.manual_seed(lowercase_     )
         _lowerCAmelCase				:     Union[str, Any]       =    np.random.RandomState(lowercase_     ).standard_normal((1, 4, 3_2, 3_2)     )
         _lowerCAmelCase				:     Optional[Any]       =    torch.from_numpy(lowercase_     ).to(device=lowercase_      ,      dtype=lowercase_     )
         _lowerCAmelCase				:     Optional[int]       =    {
             "prompt": "A painting of a squirrel eating a burger",
             "latents": latents,
             "generator": generator,
             "num_inference_steps": 3,
             "guidance_scale": 6.0,
             "output_type": "numpy",
         }
         return inputs







       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     str       =    LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""     ).to(lowercase_     )
         pipe.set_progress_bar_config(disable=lowercase_     )

         _lowerCAmelCase				:     Tuple       =    self.get_inputs(lowercase_     )
         _lowerCAmelCase				:     Optional[Any]       =    pipe(**lowercase_     ).images
         _lowerCAmelCase				:     Optional[int]       =    image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 2_5_6, 2_5_6, 3)
         _lowerCAmelCase				:     List[Any]       =    np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878]     )
         _lowerCAmelCase				:     Optional[int]       =    np.abs(expected_slice - image_slice     ).max()
         assert max_diff < 1E-3



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




       def 							__UpperCamelCase				(   self     ):
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()




       def 							__UpperCamelCase				(   self      ,      snake_case_      ,      snake_case_=torch.floataa      ,      snake_case_=0     ):
         _lowerCAmelCase				:     Optional[Any]       =    torch.manual_seed(lowercase_     )
         _lowerCAmelCase				:     str       =    np.random.RandomState(lowercase_     ).standard_normal((1, 4, 3_2, 3_2)     )
         _lowerCAmelCase				:     Dict       =    torch.from_numpy(lowercase_     ).to(device=lowercase_      ,      dtype=lowercase_     )
         _lowerCAmelCase				:     Tuple       =    {
             "prompt": "A painting of a squirrel eating a burger",
             "latents": latents,
             "generator": generator,
             "num_inference_steps": 5_0,
             "guidance_scale": 6.0,
             "output_type": "numpy",
         }
         return inputs







       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     Any       =    LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""     ).to(lowercase_     )
         pipe.set_progress_bar_config(disable=lowercase_     )

         _lowerCAmelCase				:     Optional[Any]       =    self.get_inputs(lowercase_     )
         _lowerCAmelCase				:     Optional[int]       =    pipe(**lowercase_     ).images[0]

         _lowerCAmelCase				:     Union[str, Any]       =    load_numpy(
             """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy"""     )
         _lowerCAmelCase				:     Dict       =    np.abs(expected_image - image     ).max()
         assert max_diff < 1E-3



import unittest

from datasets import load_dataset

from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow



@is_pipeline_test
@require_torch
class   snake_case_       (		unittest.TestCase       ):






   @require_torch
   def       __UpperCamelCase     (      self				:     Optional[int]  )					->						List[Any]:
       lowercase__ :   Union[str, Any]    					=				pipeline(
           task="zero-shot-audio-classification"	,						model="hf-internal-testing/tiny-clap-htsat-unfused"  )
       lowercase__ :   List[str]    					=				load_dataset("ashraq/esc50"  )
       lowercase__ :   List[Any]    					=				dataset["train"]["audio"][-1]["array"]
       lowercase__ :   Dict    					=				audio_classifier(lowercase_	,						candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]  )
       self.assertEqual(
           nested_simplify(lowercase_  )	,						[{"score": 0.5_01, "label": "Sound of a dog"}, {"score": 0.4_99, "label": "Sound of vaccum cleaner"}]	,						)






   @unittest.skip("No models are available in TF"  )
   def       __UpperCamelCase     (      self				:     str  )					->						Optional[int]:
       pass






   @slow
   @require_torch
   def       __UpperCamelCase     (      self				:     List[str]  )					->						int:
       lowercase__ :   Tuple    					=				pipeline(
           task="zero-shot-audio-classification"	,						model="laion/clap-htsat-unfused"	,						)
       # This is an audio of a dog
       lowercase__ :   Union[str, Any]    					=				load_dataset("ashraq/esc50"  )
       lowercase__ :   Tuple    					=				dataset["train"]["audio"][-1]["array"]
       lowercase__ :   List[Any]    					=				audio_classifier(lowercase_	,						candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]  )

       self.assertEqual(
           nested_simplify(lowercase_  )	,						[
               {"score": 0.9_99, "label": "Sound of a dog"},
               {"score": 0.0_01, "label": "Sound of vaccum cleaner"},
           ]	,						)

       lowercase__ :   int    					=				audio_classifier([audio] * 5	,						candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]  )
       self.assertEqual(
           nested_simplify(lowercase_  )	,						[
               [
                   {"score": 0.9_99, "label": "Sound of a dog"},
                   {"score": 0.0_01, "label": "Sound of vaccum cleaner"},
               ],
           ]
           * 5	,						)
       lowercase__ :   Tuple    					=				audio_classifier(
           [audio] * 5	,						candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]	,						batch_size=5  )
       self.assertEqual(
           nested_simplify(lowercase_  )	,						[
               [
                   {"score": 0.9_99, "label": "Sound of a dog"},
                   {"score": 0.0_01, "label": "Sound of vaccum cleaner"},
               ],
           ]
           * 5	,						)







   @unittest.skip("No models are available in TF"  )
   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						Dict:
       pass



