





"""simple docstring"""




import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, 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 PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class 			_UpperCAmelCase  (       UpperCAmelCase__      ,       UpperCAmelCase__      ,       unittest.TestCase		):



      '''simple docstring'''
      lowercase_				:			List[Any]        =       StableDiffusionXLPipeline
      lowercase_				:			List[Any]        =       TEXT_TO_IMAGE_PARAMS
      lowercase_				:			Optional[int]        =       TEXT_TO_IMAGE_BATCH_PARAMS
      lowercase_				:			Optional[Any]        =       TEXT_TO_IMAGE_IMAGE_PARAMS
      lowercase_				:			Optional[Any]        =       TEXT_TO_IMAGE_IMAGE_PARAMS

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        torch.manual_seed(0  )
        A_  :	str    						=  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') ,				attention_head_dim=(2, 4) ,				use_linear_projection=__A ,				addition_embed_type='text_time' ,				addition_time_embed_dim=8 ,				transformer_layers_per_block=(1, 2) ,				projection_class_embeddings_input_dim=8_0 ,				cross_attention_dim=6_4 ,				)
        A_  :	Dict    						=  EulerDiscreteScheduler(
            beta_start=0.0_00_85 ,				beta_end=0.0_12 ,				steps_offset=1 ,				beta_schedule='scaled_linear' ,				timestep_spacing='leading' ,				)
        torch.manual_seed(0  )
        A_  :	int    						=  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 ,				sample_size=1_2_8 ,				)
        torch.manual_seed(0  )
        A_  :	Dict    						=  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 ,				hidden_act='gelu' ,				projection_dim=3_2 ,				)
        A_  :	List[Any]    						=  CLIPTextModel(__A  )
        A_  :	int    						=  CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ,				local_files_only=__A  )

        A_  :	Optional[Any]    						=  CLIPTextModelWithProjection(__A  )
        A_  :	Optional[Any]    						=  CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ,				local_files_only=__A  )

        A_  :	Optional[Any]    						=  {
            "unet": unet,
            "scheduler": scheduler,
            "vae": vae,
            "text_encoder": text_encoder,
            "tokenizer": tokenizer,
            "text_encoder_2": text_encoder_a,
            "tokenizer_2": tokenizer_a,
            # "safety_checker": None,
            # "feature_extractor": None,
        }
        return components

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_=0  ):

        """simple docstring"""

        if str(__A  ).startswith('mps'  ):
          A_  :	Any    						=  torch.manual_seed(__A  )
        else:
          A_  :	Union[str, Any]    						=  torch.Generator(device=__A  ).manual_seed(__A  )
        A_  :	Union[str, Any]    						=  {
            "prompt": "A painting of a squirrel eating a burger",
            "generator": generator,
            "num_inference_steps": 2,
            "guidance_scale": 5.0,
            "output_type": "numpy",
        }
        return inputs

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Optional[Any]    						=  "cpu"  # ensure determinism for the device-dependent torch.Generator
        A_  :	Optional[int]    						=  self.get_dummy_components()
        A_  :	Dict    						=  StableDiffusionXLPipeline(**__A  )
        A_  :	str    						=  sd_pipe.to(__A  )
        sd_pipe.set_progress_bar_config(disable=__A  )

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

        assert image.shape == (1, 6_4, 6_4, 3)
        A_  :	Tuple    						=  np.array([0.58_73, 0.61_28, 0.47_97, 0.51_22, 0.56_74, 0.46_39, 0.52_27, 0.51_49, 0.47_47]  )

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

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Tuple    						=  self.get_dummy_components()
        A_  :	Optional[Any]    						=  StableDiffusionXLPipeline(**__A  )
        A_  :	Dict    						=  sd_pipe.to(__A  )
        A_  :	Optional[Any]    						=  sd_pipe.to(__A  )
        sd_pipe.set_progress_bar_config(disable=__A  )

        # forward without prompt embeds
        A_  :	List[Any]    						=  self.get_dummy_inputs(__A  )
        A_  :	int    						=  3 * ["this is a negative prompt"]
        A_  :	Tuple    						=  negative_prompt
        A_  :	Any    						=  3 * [inputs["prompt"]]

        A_  :	str    						=  sd_pipe(**__A  )
        A_  :	Any    						=  output.images[0, -3:, -3:, -1]

        # forward with prompt embeds
        A_  :	List[str]    						=  self.get_dummy_inputs(__A  )
        A_  :	Optional[Any]    						=  3 * ["this is a negative prompt"]
        A_  :	str    						=  3 * [inputs.pop('prompt'  )]

        (
            A_     
        )  :	Optional[Any]    						=  sd_pipe.encode_prompt(__A ,				negative_prompt=__A  )

        A_  :	Dict    						=  sd_pipe(
            **__A ,				prompt_embeds=__A ,				negative_prompt_embeds=__A ,				pooled_prompt_embeds=__A ,				negative_pooled_prompt_embeds=__A ,				)
        A_  :	Tuple    						=  output.images[0, -3:, -3:, -1]

        # make sure that it's equal
        assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()  ).max() < 1E-4

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        super().test_attention_slicing_forward_pass(expected_max_diff=3E-3  )

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        super().test_inference_batch_single_identical(expected_max_diff=3E-3  )


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



      '''simple docstring'''

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_="cpu" ,				snake_case_=torch.floataa ,				snake_case_=0  ):

        """simple docstring"""

        A_  :	Tuple    						=  torch.Generator(device=__A  ).manual_seed(__A  )
        A_  :	str    						=  np.random.RandomState(__A  ).standard_normal((1, 4, 6_4, 6_4)  )
        A_  :	Dict    						=  torch.from_numpy(__A  ).to(device=__A ,				dtype=__A  )
        A_  :	Tuple    						=  {
            "prompt": "a photograph of an astronaut riding a horse",
            "latents": latents,
            "generator": generator,
            "num_inference_steps": 3,
            "guidance_scale": 7.5,
            "output_type": "numpy",
        }
        return inputs

      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Union[str, Any]    						=  DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base'  )
        pipe.to(__A  )
        pipe.set_progress_bar_config(disable=__A  )

        A_  :	Optional[Any]    						=  self.get_inputs(__A  )
        A_  :	int    						=  pipe(**__A  ).images
        A_  :	Dict    						=  image[0, -3:, -3:, -1].flatten()

        assert image.shape == (1, 5_1_2, 5_1_2, 3)
        A_  :	Optional[Any]    						=  np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]  )
        assert np.abs(image_slice - expected_slice  ).max() < 7E-3






"""simple docstring"""




def 						UpperCAmelCase__		(					_UpperCAmelCase			, _UpperCAmelCase ):






  """simple docstring"""





  A_  :	Any    						=  len(_UpperCAmelCase )
  # Create a stack and push index of fist element to it
  A_  :	List[Any]    						=  []
  st.append(0 )

  # Span value of first element is always 1
  A_  :	List[str]    						=  1

  # Calculate span values for rest of the elements
  for i in range(1			, _UpperCAmelCase ):
    # Pop elements from stack while stack is not
    # empty and top of stack is smaller than price[i]
    while len(_UpperCAmelCase ) > 0 and price[st[0]] <= price[i]:
      st.pop()

    # If stack becomes empty, then price[i] is greater
    # than all elements on left of it, i.e. price[0],
    # price[1], ..price[i-1]. Else the price[i]  is
    # greater than elements after top of stack
    A_  :	Union[str, Any]    						=  i + 1 if len(_UpperCAmelCase ) <= 0 else (i - st[0])

    # Push this element to stack
    st.append(_UpperCAmelCase )





def 						UpperCAmelCase__		(					_UpperCAmelCase			, _UpperCAmelCase ):






  """simple docstring"""





  for i in range(0			, _UpperCAmelCase ):
    print(arr[i]			, end=' ' )


# Driver program to test above function
lowerCamelCase_					:						List[Any]      = [10, 4, 5, 90, 1_20, 80]
lowerCamelCase_					:						Optional[Any]      = [0 for i in range(len(price) + 1)]

# Fill the span values in array S[]
calculation_span(price, S)





print_array(S, len(price))