
"""simple docstring"""
import gc
import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class 			UpperCamelCase      (							__lowerCAmelCase      ,       __lowerCAmelCase      ,       unittest.TestCase  ):
					A__      =			StableDiffusionXLImgaImgPipeline
					A__      =			TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
					A__      =			PipelineTesterMixin.required_optional_params - {'''latents'''}
					A__      =			TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
					A__      =			IMAGE_TO_IMAGE_IMAGE_PARAMS
					A__      =			IMAGE_TO_IMAGE_IMAGE_PARAMS
					def 				__SCREAMING_SNAKE_CASE							(     self				):




							"""simple docstring"""


							torch.manual_seed(0				)
							_SCREAMING_SNAKE_CASE   :				Tuple							    = 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  ,     )
							_SCREAMING_SNAKE_CASE   :				Optional[Any]							    = EulerDiscreteScheduler(
							    beta_start=0.00_085  ,     beta_end=0.012  ,     steps_offset=1  ,     beta_schedule="scaled_linear"  ,     timestep_spacing="leading"  ,     )
							torch.manual_seed(0				)
							_SCREAMING_SNAKE_CASE   :				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				)
							_SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = 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  ,     )
							_SCREAMING_SNAKE_CASE   :				List[str]							    = CLIPTextModel(lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				int							    = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"  ,     local_files_only=lowerCAmelCase_				)

							_SCREAMING_SNAKE_CASE   :				Optional[Any]							    = CLIPTextModelWithProjection(lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				int							    = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"  ,     local_files_only=lowerCAmelCase_				)

							_SCREAMING_SNAKE_CASE   :				Union[str, 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 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__=0				):




							"""simple docstring"""


							_SCREAMING_SNAKE_CASE   :				Dict							    = floats_tensor((1, 3, 32, 32)  ,     rng=random.Random(lowerCAmelCase_				)				).to(lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				str							    = image / 2 + 0.5
							if str(lowerCAmelCase_				).startswith("mps"				):
									_SCREAMING_SNAKE_CASE   :				Tuple							    = torch.manual_seed(lowerCAmelCase_				)
							else:
									_SCREAMING_SNAKE_CASE   :				int							    = torch.Generator(device=lowerCAmelCase_				).manual_seed(lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				str							    = {
							    "prompt": "A painting of a squirrel eating a burger",
							    "image": image,
							    "generator": generator,
							    "num_inference_steps": 2,
							    "guidance_scale": 5.0,
							    "output_type": "numpy",
							    "strength": 0.75,
							}
							return inputs
					def 				__SCREAMING_SNAKE_CASE							(     self				):




							"""simple docstring"""


							_SCREAMING_SNAKE_CASE   :				Optional[Any]							    = "cpu"  # ensure determinism for the device-dependent torch.Generator
							_SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = self.get_dummy_components()
							_SCREAMING_SNAKE_CASE   :				List[str]							    = StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				Optional[int]							    = sd_pipe.to(lowerCAmelCase_				)
							sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_				)

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

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

							_SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165]				)

							assert np.abs(image_slice.flatten() - expected_slice				).max() < 1E-2
					def 				__SCREAMING_SNAKE_CASE							(     self				):




							"""simple docstring"""


							super().test_attention_slicing_forward_pass(expected_max_diff=3E-3				)
					def 				__SCREAMING_SNAKE_CASE							(     self				):




							"""simple docstring"""


							super().test_inference_batch_single_identical(expected_max_diff=3E-3				)
					def 				__SCREAMING_SNAKE_CASE							(     self				):




							"""simple docstring"""


							pass




					def 				__SCREAMING_SNAKE_CASE							(     self				):




							"""simple docstring"""


							_SCREAMING_SNAKE_CASE   :				List[str]							    = self.get_dummy_components()
							_SCREAMING_SNAKE_CASE   :				Any							    = StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				Optional[Any]							    = sd_pipe.to(lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				List[Any]							    = sd_pipe.to(lowerCAmelCase_				)
							sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_				)

							# forward without prompt embeds
							_SCREAMING_SNAKE_CASE   :				Optional[Any]							    = self.get_dummy_inputs(lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				Optional[int]							    = 3 * ["this is a negative prompt"]
							_SCREAMING_SNAKE_CASE   :				Optional[Any]							    = negative_prompt
							_SCREAMING_SNAKE_CASE   :				Any							    = 3 * [inputs["prompt"]]

							_SCREAMING_SNAKE_CASE   :				List[str]							    = sd_pipe(**lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				Dict							    = output.images[0, -3:, -3:, -1]

							# forward with prompt embeds
							_SCREAMING_SNAKE_CASE   :				str							    = self.get_dummy_inputs(lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				int							    = 3 * ["this is a negative prompt"]
							_SCREAMING_SNAKE_CASE   :				Optional[int]							    = 3 * [inputs.pop("prompt"				)]

							(
							    (
							    _SCREAMING_SNAKE_CASE						
							)    ,		(
							    _SCREAMING_SNAKE_CASE						
							)    ,		(
							    _SCREAMING_SNAKE_CASE						
							)    ,		(
							    _SCREAMING_SNAKE_CASE						
							)    ,								
							)   :				Dict							    = sd_pipe.encode_prompt(lowerCAmelCase_  ,     negative_prompt=lowerCAmelCase_				)

							_SCREAMING_SNAKE_CASE   :				Dict							    = sd_pipe(
							    **lowerCAmelCase_  ,     prompt_embeds=lowerCAmelCase_  ,     negative_prompt_embeds=lowerCAmelCase_  ,     pooled_prompt_embeds=lowerCAmelCase_  ,     negative_pooled_prompt_embeds=lowerCAmelCase_  ,     )
							_SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = 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
@slow
@require_torch_gpu
class 			UpperCamelCase      (							unittest.TestCase  ):
					def 				__SCREAMING_SNAKE_CASE							(     self				):




							"""simple docstring"""


							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()
					def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__="cpu"  ,     snake_case__=torch.floataa  ,     snake_case__=0				):




							"""simple docstring"""


							_SCREAMING_SNAKE_CASE   :				Any							    = torch.Generator(device=lowerCAmelCase_				).manual_seed(lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				List[str]							    = np.random.RandomState(lowerCAmelCase_				).standard_normal((1, 4, 64, 64)				)
							_SCREAMING_SNAKE_CASE   :				int							    = torch.from_numpy(lowerCAmelCase_				).to(device=lowerCAmelCase_  ,     dtype=lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				List[str]							    = {
							    "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 				__SCREAMING_SNAKE_CASE							(     self				):




							"""simple docstring"""


							_SCREAMING_SNAKE_CASE   :				int							    = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base"				)
							pipe.to(lowerCAmelCase_				)
							pipe.set_progress_bar_config(disable=lowerCAmelCase_				)

							_SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = self.get_inputs(lowerCAmelCase_				)
							_SCREAMING_SNAKE_CASE   :				List[Any]							    = pipe(**lowerCAmelCase_				).images
							_SCREAMING_SNAKE_CASE   :				str							    = image[0, -3:, -3:, -1].flatten()

							assert image.shape == (1, 512, 512, 3)
							_SCREAMING_SNAKE_CASE   :				Optional[Any]							    = np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506]				)
							assert np.abs(image_slice - expected_slice				).max() < 7E-3





"""simple docstring"""
from collections.abc import Iterable
from typing import Any
class 			UpperCamelCase      :
     def __init__(     self  ,     snake_case__ = None				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[str]							    = value
       _SCREAMING_SNAKE_CASE   :				Node | None							    = None  # Added in order to delete a node easier
       _SCREAMING_SNAKE_CASE   :				Node | None							    = None
       _SCREAMING_SNAKE_CASE   :				Node | None							    = None




     def __repr__(     self				):




       """simple docstring"""


       from pprint import pformat

       if self.left is None and self.right is None:
         return str(self.value				)
       return pformat({F'''{self.value}''': (self.left, self.right)}  ,     indent=1				)
class 			UpperCamelCase      :
     def __init__(     self  ,     snake_case__ = None				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[str]							    = root
     def __str__(     self				):




       """simple docstring"""


       return str(self.root				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       if new_children is not None:  # reset its kids
         _SCREAMING_SNAKE_CASE   :				Dict							    = node.parent
       if node.parent is not None:  # reset its parent
         if self.is_right(snake_case__				):  # If it is the right children
           _SCREAMING_SNAKE_CASE   :				Any							    = new_children
         else:
           _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = new_children
       else:
         _SCREAMING_SNAKE_CASE   :				Any							    = new_children
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       if node.parent and node.parent.right:
         return node == node.parent.right
       return False
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       return self.root is None
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = Node(snake_case__				)  # create a new Node
       if self.empty():  # if Tree is empty
         _SCREAMING_SNAKE_CASE   :				str							    = new_node  # set its root
       else:  # Tree is not empty
         _SCREAMING_SNAKE_CASE   :				Dict							    = self.root  # from root
         if parent_node is None:
           return
         while True:  # While we don't get to a leaf
           if value < parent_node.value:  # We go left
             if parent_node.left is None:
               _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = new_node  # We insert the new node in a leaf
               break
             else:
               _SCREAMING_SNAKE_CASE   :				int							    = parent_node.left
           else:
             if parent_node.right is None:
               _SCREAMING_SNAKE_CASE   :				str							    = new_node
               break
             else:
               _SCREAMING_SNAKE_CASE   :				Optional[int]							    = parent_node.right
         _SCREAMING_SNAKE_CASE   :				Any							    = parent_node
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     *snake_case__				):




       """simple docstring"""


       for value in values:
         self.__insert(snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       if self.empty():
         raise IndexError("Warning: Tree is empty! please use another."				)
       else:
         _SCREAMING_SNAKE_CASE   :				Optional[int]							    = self.root
         # use lazy evaluation here to avoid NoneType Attribute error
         while node is not None and node.value is not value:
           _SCREAMING_SNAKE_CASE   :				List[Any]							    = node.left if value < node.value else node.right
         return node
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__ = None				):




       """simple docstring"""


       if node is None:
         if self.root is None:
           return None
         _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = self.root

       if not self.empty():
         while node.right is not None:
           _SCREAMING_SNAKE_CASE   :				Dict							    = node.right
       return node
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__ = None				):




       """simple docstring"""


       if node is None:
         _SCREAMING_SNAKE_CASE   :				List[Any]							    = self.root
       if self.root is None:
         return None
       if not self.empty():
         _SCREAMING_SNAKE_CASE   :				Any							    = self.root
         while node.left is not None:
           _SCREAMING_SNAKE_CASE   :				Optional[int]							    = node.left
       return node
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Dict							    = self.search(snake_case__				)  # Look for the node with that label
       if node is not None:
         if node.left is None and node.right is None:  # If it has no children
           self.__reassign_nodes(snake_case__  ,     snake_case__				)
         elif node.left is None:  # Has only right children
           self.__reassign_nodes(snake_case__  ,     node.right				)
         elif node.right is None:  # Has only left children
           self.__reassign_nodes(snake_case__  ,     node.left				)
         else:
           _SCREAMING_SNAKE_CASE   :				Dict							    = self.get_max(
               node.left				)  # Gets the max value of the left branch
           self.remove(tmp_node.value				)  # type: ignore
           _SCREAMING_SNAKE_CASE   :				List[Any]							    = (
               tmp_node.value  # type: ignore
           )  # Assigns the value to the node to delete and keep tree structure
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       if node is not None:
         yield node  # Preorder Traversal
         yield from self.preorder_traverse(node.left				)
         yield from self.preorder_traverse(node.right				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__=None				):




       """simple docstring"""


       if traversal_function is None:
         return self.preorder_traverse(self.root				)
       else:
         return traversal_function(self.root				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       if node:
         self.inorder(snake_case__  ,     node.left				)
         arr.append(node.value				)
         self.inorder(snake_case__  ,     node.right				)




     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				list[int]							    = []
       self.inorder(snake_case__  ,     snake_case__				)  # append all values to list using inorder traversal
       return arr[k - 1]





def    _lowerCAmelCase    (     lowerCamelCase__							:							Node | None				)  ->    list[Node]:
  _SCREAMING_SNAKE_CASE   :				Optional[int]							    = []
  if curr_node is not None:
    _SCREAMING_SNAKE_CASE   :				int							    = postorder(curr_node.left				) + postorder(curr_node.right				) + [curr_node]
  return node_list





def    _lowerCAmelCase    (     )  ->    None:
  _SCREAMING_SNAKE_CASE   :				Any							    = (8, 3, 6, 1, 1_0, 1_4, 1_3, 4, 7)
  _SCREAMING_SNAKE_CASE   :				List[Any]							    = BinarySearchTree()
  for i in testlist:
    t.insert(lowerCamelCase__				)

  # Prints all the elements of the list in order traversal
  print(lowerCamelCase__				)

  if t.search(6				) is not None:
    print("The value 6 exists"				)
  else:
    print("The value 6 doesn't exist"				)

  if t.search(-1				) is not None:
    print("The value -1 exists"				)
  else:
    print("The value -1 doesn't exist"				)

  if not t.empty():
    print("Max Value: ",						t.get_max().value				)  # type: ignore
    print("Min Value: ",						t.get_min().value				)  # type: ignore

  for i in testlist:
    t.remove(lowerCamelCase__				)
    print(lowerCamelCase__				)


if __name__ == "__main__":
      import doctest

      doctest.testmod(verbose=True)



