


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'''




   __A			:				int							=		StableDiffusionXLPipeline
   __A			:				List[Any]							=		TEXT_TO_IMAGE_PARAMS
   __A			:				str							=		TEXT_TO_IMAGE_BATCH_PARAMS
   __A			:				str							=		TEXT_TO_IMAGE_IMAGE_PARAMS
   __A			:				List[Any]							=		TEXT_TO_IMAGE_IMAGE_PARAMS






   def _snake_case   (		self			):






     """simple docstring"""





     torch.manual_seed(0			)
     lowerCamelCase			: Union[str, Any]   =    UNetaDConditionModel(
         block_out_channels=(32, 64)						,    layers_per_block=2						,    sample_size=32						,    in_channels=4						,    out_channels=4						,    down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")						,    up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")						,    attention_head_dim=(2, 4)						,    use_linear_projection=lowerCamelCase__						,    addition_embed_type="text_time"						,    addition_time_embed_dim=8						,    transformer_layers_per_block=(1, 2)						,    projection_class_embeddings_input_dim=80						,    cross_attention_dim=64						,    )
     lowerCamelCase			: Optional[int]   =    EulerDiscreteScheduler(
         beta_start=0.00085						,    beta_end=0.012						,    steps_offset=1						,    beta_schedule="scaled_linear"						,    timestep_spacing="leading"						,    )
     torch.manual_seed(0			)
     lowerCamelCase			: Any   =    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			)
     lowerCamelCase			: str   =    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=32						,    )
     lowerCamelCase			: int   =    CLIPTextModel(lowerCamelCase__			)
     lowerCamelCase			: Optional[int]   =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						,    local_files_only=lowerCamelCase__			)

     lowerCamelCase			: Union[str, Any]   =    CLIPTextModelWithProjection(lowerCamelCase__			)
     lowerCamelCase			: Union[str, Any]   =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						,    local_files_only=lowerCamelCase__			)

     lowerCamelCase			: List[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 _snake_case   (		self						,    __A						,    __A=0			):






     """simple docstring"""





     if str(lowerCamelCase__			).startswith("mps"			):
       lowerCamelCase			: List[str]   =    torch.manual_seed(lowerCamelCase__			)
     else:
       lowerCamelCase			: str   =    torch.Generator(device=lowerCamelCase__			).manual_seed(lowerCamelCase__			)
     lowerCamelCase			: Optional[int]   =    {
         "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 _snake_case   (		self			):






     """simple docstring"""





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

     lowerCamelCase			: List[Any]   =    self.get_dummy_inputs(lowerCamelCase__			)
     lowerCamelCase			: Optional[int]   =    sd_pipe(**lowerCamelCase__			).images
     lowerCamelCase			: Dict   =    image[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)
     lowerCamelCase			: Tuple   =    np.array([0.5873, 0.6128, 0.4797, 0.5122, 0.5674, 0.4639, 0.5227, 0.5149, 0.4747]			)

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






   def _snake_case   (		self			):






     """simple docstring"""





     lowerCamelCase			: List[Any]   =    self.get_dummy_components()
     lowerCamelCase			: Any   =    StableDiffusionXLPipeline(**lowerCamelCase__			)
     lowerCamelCase			: List[Any]   =    sd_pipe.to(lowerCamelCase__			)
     lowerCamelCase			: Optional[int]   =    sd_pipe.to(lowerCamelCase__			)
     sd_pipe.set_progress_bar_config(disable=lowerCamelCase__			)

     # forward without prompt embeds
     lowerCamelCase			: Union[str, Any]   =    self.get_dummy_inputs(lowerCamelCase__			)
     lowerCamelCase			: Union[str, Any]   =    3 * ["this is a negative prompt"]
     lowerCamelCase			: int   =    negative_prompt
     lowerCamelCase			: List[Any]   =    3 * [inputs["prompt"]]

     lowerCamelCase			: str   =    sd_pipe(**lowerCamelCase__			)
     lowerCamelCase			: List[str]   =    output.images[0, -3:, -3:, -1]

     # forward with prompt embeds
     lowerCamelCase			: List[Any]   =    self.get_dummy_inputs(lowerCamelCase__			)
     lowerCamelCase			: Dict   =    3 * ["this is a negative prompt"]
     lowerCamelCase			: Any   =    3 * [inputs.pop("prompt"			)]

     (
         (
         lowerCamelCase  
     )   ,     (
         lowerCamelCase  
     )   ,     (
         lowerCamelCase  
     )   ,     (
         lowerCamelCase  
     )   ,       
     )			: Dict   =    sd_pipe.encode_prompt(lowerCamelCase__						,    negative_prompt=lowerCamelCase__			)

     lowerCamelCase			: int   =    sd_pipe(
         **lowerCamelCase__						,    prompt_embeds=lowerCamelCase__						,    negative_prompt_embeds=lowerCamelCase__						,    pooled_prompt_embeds=lowerCamelCase__						,    negative_pooled_prompt_embeds=lowerCamelCase__						,    )
     lowerCamelCase			: Dict   =    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 _snake_case   (		self			):






     """simple docstring"""





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






   def _snake_case   (		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 _snake_case   (		self			):






     """simple docstring"""





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






   def _snake_case   (		self						,    __A						,    __A="cpu"						,    __A=torch.floataa						,    __A=0			):






     """simple docstring"""





     lowerCamelCase			: Union[str, Any]   =    torch.Generator(device=lowerCamelCase__			).manual_seed(lowerCamelCase__			)
     lowerCamelCase			: Any   =    np.random.RandomState(lowerCamelCase__			).standard_normal((1, 4, 64, 64)			)
     lowerCamelCase			: str   =    torch.from_numpy(lowerCamelCase__			).to(device=lowerCamelCase__						,    dtype=lowerCamelCase__			)
     lowerCamelCase			: Dict   =    {
         "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 _snake_case   (		self			):






     """simple docstring"""





     lowerCamelCase			: str   =    DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base"			)
     pipe.to(lowerCamelCase__			)
     pipe.set_progress_bar_config(disable=lowerCamelCase__			)

     lowerCamelCase			: Optional[Any]   =    self.get_inputs(lowerCamelCase__			)
     lowerCamelCase			: Optional[Any]   =    pipe(**lowerCamelCase__			).images
     lowerCamelCase			: List[str]   =    image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 512, 512, 3)
     lowerCamelCase			: Tuple   =    np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506]			)
     assert np.abs(image_slice - expected_slice			).max() < 7e-3







def 		lowercase_(  SCREAMING_SNAKE_CASE_				,						SCREAMING_SNAKE_CASE_     ):


  '''simple docstring'''

  sequence.append(SCREAMING_SNAKE_CASE_     )

  lowerCamelCase			: str   =    0
  while sequence[index] != target:
    index += 1

  sequence.pop()

  if index == len(SCREAMING_SNAKE_CASE_     ):
    return None

  return index


if __name__ == "__main__":
   _snake_case					=					input('''Enter numbers separated by comma:\n''').strip()
   _snake_case					=					[int(item) for item in user_input.split(''',''')]

   _snake_case					=					input('''Enter a single number to be found in the list:\n''')
   _snake_case					=					int(target_input)
   _snake_case					=					sentinel_linear_search(sequence, target)
   if result is not None:
      print(f'''{target} found at positions: {result}''')
   else:
      print('''Not found''')



