




'''simple docstring'''





import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


UpperCamelCase_		:     List[Any]          =		False

@skip_mps
class   _a							(		__lowerCAmelCase   ,   __lowerCAmelCase   ,   __lowerCAmelCase   ,   unittest.TestCase				):
     SCREAMING_SNAKE_CASE_				:       int       							=		StableDiffusionAttendAndExcitePipeline
     SCREAMING_SNAKE_CASE_				:       Union[str, Any]       							=		False
     SCREAMING_SNAKE_CASE_				:       Union[str, Any]       							=		TEXT_TO_IMAGE_PARAMS
     SCREAMING_SNAKE_CASE_				:       Any       							=		TEXT_TO_IMAGE_BATCH_PARAMS.union({"""token_indices"""}				)
     SCREAMING_SNAKE_CASE_				:       str       							=		TEXT_TO_IMAGE_IMAGE_PARAMS
     SCREAMING_SNAKE_CASE_				:       int       							=		TEXT_TO_IMAGE_IMAGE_PARAMS






     @classmethod
     def 							_lowercase      (					cls       )				->     int:
          super().setUpClass()
          torch.use_deterministic_algorithms(_SCREAMING_SNAKE_CASE       )






     @classmethod
     def 							_lowercase      (					cls       )				->     Any:
          super().tearDownClass()
          torch.use_deterministic_algorithms(_SCREAMING_SNAKE_CASE       )






     def 							_lowercase      (					self       )				->     List[Any]:
          torch.manual_seed(0       )
          _snake_case				= UNetaDConditionModel(
              block_out_channels=(32, 64)   ,layers_per_block=1   ,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=_SCREAMING_SNAKE_CASE   ,)
          _snake_case				= DDIMScheduler(
              beta_start=0.0_0_0_8_5   ,beta_end=0.0_1_2   ,beta_schedule="scaled_linear"   ,clip_sample=_SCREAMING_SNAKE_CASE   ,set_alpha_to_one=_SCREAMING_SNAKE_CASE   ,)
          torch.manual_seed(0       )
          _snake_case				= 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       )
          _snake_case				= 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=1_000   ,hidden_act="gelu"   ,projection_dim=512   ,)
          _snake_case				= CLIPTextModel(_SCREAMING_SNAKE_CASE       )
          _snake_case				= CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

          _snake_case				= {
              "unet": unet,
              "scheduler": scheduler,
              "vae": vae,
              "text_encoder": text_encoder,
              "tokenizer": tokenizer,
              "safety_checker": None,
              "feature_extractor": None,
          }

          return components






     def 							_lowercase      (					self   ,_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE=0       )				->     Optional[Any]:
          if str(_SCREAMING_SNAKE_CASE       ).startswith("mps"       ):
               _snake_case				= torch.manual_seed(_SCREAMING_SNAKE_CASE       )
          else:
               _snake_case				= torch.Generator(device=_SCREAMING_SNAKE_CASE       ).manual_seed(_SCREAMING_SNAKE_CASE       )
          _snake_case				= _snake_case				= {
              "prompt": "a cat and a frog",
              "token_indices": [2, 5],
              "generator": generator,
              "num_inference_steps": 1,
              "guidance_scale": 6.0,
              "output_type": "numpy",
              "max_iter_to_alter": 2,
              "thresholds": {0: 0.7},
          }
          return inputs






     def 							_lowercase      (					self       )				->     List[str]:
          _snake_case				= "cpu"

          _snake_case				= self.get_dummy_components()
          _snake_case				= self.pipeline_class(**_SCREAMING_SNAKE_CASE       )
          pipe.to(_SCREAMING_SNAKE_CASE       )
          pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE       )

          _snake_case				= self.get_dummy_inputs(_SCREAMING_SNAKE_CASE       )
          _snake_case				= pipe(**_SCREAMING_SNAKE_CASE       ).images
          _snake_case				= image[0, -3:, -3:, -1]

          self.assertEqual(image.shape   ,(1, 64, 64, 3)       )
          _snake_case				= np.array(
              [0.6_3_9_0_5_3_6_4, 0.6_2_8_9_7_3_0_7, 0.4_8_5_9_9_0_1_7, 0.5_1_3_3_6_2_4, 0.5_5_5_0_0_4_8, 0.4_5_7_6_9_5_1_6, 0.5_0_3_2_6_9_7_3, 0.5_0_2_3_1_3_9, 0.4_5_3_8_4_4_9_6]       )
          _snake_case				= np.abs(image_slice.flatten() - expected_slice       ).max()
          self.assertLessEqual(_SCREAMING_SNAKE_CASE   ,1e-3       )






     def 							_lowercase      (					self       )				->     List[str]:
          super().test_cpu_offload_forward_pass(expected_max_diff=5e-4       )






     def 							_lowercase      (					self       )				->     List[Any]:
          # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
          self._test_inference_batch_consistent(batch_sizes=[1, 2]       )






     def 							_lowercase      (					self       )				->     Any:
          self._test_inference_batch_single_identical(batch_size=2   ,expected_max_diff=7e-4       )






     def 							_lowercase      (					self       )				->     Tuple:
          super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3       )






     def 							_lowercase      (					self       )				->     Optional[Any]:
          super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4       )






     def 							_lowercase      (					self       )				->     Optional[int]:
          super().test_save_load_local(expected_max_difference=5e-4       )






     def 							_lowercase      (					self       )				->     Any:
          super().test_save_load_optional_components(expected_max_difference=4e-4       )







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






     @classmethod
     def 							_lowercase      (					cls       )				->     List[str]:
          super().setUpClass()
          torch.use_deterministic_algorithms(_SCREAMING_SNAKE_CASE       )






     @classmethod
     def 							_lowercase      (					cls       )				->     Union[str, Any]:
          super().tearDownClass()
          torch.use_deterministic_algorithms(_SCREAMING_SNAKE_CASE       )






     def 							_lowercase      (					self       )				->     List[Any]:
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()






     def 							_lowercase      (					self       )				->     Union[str, Any]:
          _snake_case				= torch.manual_seed(51       )

          _snake_case				= StableDiffusionAttendAndExcitePipeline.from_pretrained(
              "CompVis/stable-diffusion-v1-4"   ,safety_checker=_SCREAMING_SNAKE_CASE   ,torch_dtype=torch.floataa       )
          pipe.to("cuda"       )

          _snake_case				= "a painting of an elephant with glasses"
          _snake_case				= [5, 7]

          _snake_case				= pipe(
              prompt=_SCREAMING_SNAKE_CASE   ,token_indices=_SCREAMING_SNAKE_CASE   ,guidance_scale=7.5   ,generator=_SCREAMING_SNAKE_CASE   ,num_inference_steps=5   ,max_iter_to_alter=5   ,output_type="numpy"   ,).images[0]

          _snake_case				= load_numpy(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy"       )
          assert np.abs((expected_image - image).max()       ) < 5e-1








'''simple docstring'''





from pathlib import Path
from typing import List

from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import get_tests_dir, is_tool_test
from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image


UpperCamelCase_		:     int          =		['''text''', '''image''', '''audio''']





def       __a      (  _UpperCamelCase:       List[str]       )		->					Dict:

     """simple docstring"""




     _snake_case				= []

     for input_type in input_types:
          if input_type == "text":
               inputs.append("Text input"       )
          elif input_type == "image":
               inputs.append(
                   Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO"       )       ) / "000000039769.png"       ).resize((512, 512)       )       )
          elif input_type == "audio":
               inputs.append(torch.ones(3_000       )       )
          elif isinstance(_UpperCamelCase   ,		_UpperCamelCase       ):
               inputs.append(create_inputs(_UpperCamelCase       )       )
          else:
               raise ValueError(F"""Invalid type requested: {input_type}"""       )

     return inputs





def       __a      (  _UpperCamelCase:       List       )		->					Dict:

     """simple docstring"""




     _snake_case				= []

     for output in outputs:
          if isinstance(_UpperCamelCase   ,		(str, AgentText)       ):
               output_types.append("text"       )
          elif isinstance(_UpperCamelCase   ,		(Image.Image, AgentImage)       ):
               output_types.append("image"       )
          elif isinstance(_UpperCamelCase   ,		(torch.Tensor, AgentAudio)       ):
               output_types.append("audio"       )
          else:
               raise ValueError(F"""Invalid output: {output}"""       )

     return output_types





@is_tool_test
class   _a							:






     def 							_lowercase      (					self       )				->     Any:
          self.assertTrue(hasattr(self.tool   ,"inputs"       )       )
          self.assertTrue(hasattr(self.tool   ,"outputs"       )       )

          _snake_case				= self.tool.inputs
          for _input in inputs:
               if isinstance(_input   ,_SCREAMING_SNAKE_CASE       ):
                    for __input in _input:
                         self.assertTrue(__input in authorized_types       )
               else:
                    self.assertTrue(_input in authorized_types       )

          _snake_case				= self.tool.outputs
          for _output in outputs:
               self.assertTrue(_output in authorized_types       )






     def 							_lowercase      (					self       )				->     Any:
          _snake_case				= create_inputs(self.tool.inputs       )
          _snake_case				= self.tool(*_SCREAMING_SNAKE_CASE       )

          # There is a single output
          if len(self.tool.outputs       ) == 1:
               _snake_case				= [outputs]

          self.assertListEqual(output_types(_SCREAMING_SNAKE_CASE       )   ,self.tool.outputs       )






     def 							_lowercase      (					self       )				->     str:
          self.assertTrue(hasattr(self.tool   ,"description"       )       )
          self.assertTrue(hasattr(self.tool   ,"default_checkpoint"       )       )
          self.assertTrue(self.tool.description.startswith("This is a tool that"       )       )






     def 							_lowercase      (					self       )				->     Tuple:
          _snake_case				= create_inputs(self.tool.inputs       )
          _snake_case				= self.tool(*_SCREAMING_SNAKE_CASE       )

          if not isinstance(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       ):
               _snake_case				= [outputs]

          self.assertEqual(len(_SCREAMING_SNAKE_CASE       )   ,len(self.tool.outputs       )       )

          for output, output_type in zip(_SCREAMING_SNAKE_CASE   ,self.tool.outputs       ):
               _snake_case				= AGENT_TYPE_MAPPING[output_type]
               self.assertTrue(isinstance(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       )       )






     def 							_lowercase      (					self       )				->     Optional[Any]:
          _snake_case				= create_inputs(self.tool.inputs       )

          _snake_case				= []

          for _input, input_type in zip(_SCREAMING_SNAKE_CASE   ,self.tool.inputs       ):
               if isinstance(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       ):
                    _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input       ) for _input_type in input_type]       )
               else:
                    _inputs.append(AGENT_TYPE_MAPPING[input_type](_input       )       )

        # Should not raise an error
          _snake_case				= self.tool(*_SCREAMING_SNAKE_CASE       )

          if not isinstance(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       ):
               _snake_case				= [outputs]

          self.assertEqual(len(_SCREAMING_SNAKE_CASE       )   ,len(self.tool.outputs       )       )


