


"""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      =   False







@skip_mps
class lowerCAmelCase_						(			lowerCamelCase__ ,						lowerCamelCase__ ,						lowerCamelCase__ ,						unittest.TestCase	):

 '''simple docstring'''

 __snake_case												=  StableDiffusionAttendAndExcitePipeline
 __snake_case												=  False
 __snake_case												=  TEXT_TO_IMAGE_PARAMS
 __snake_case												=  TEXT_TO_IMAGE_BATCH_PARAMS.union({"token_indices"}	)
 __snake_case												=  TEXT_TO_IMAGE_IMAGE_PARAMS
 __snake_case												=  TEXT_TO_IMAGE_IMAGE_PARAMS



 @classmethod
 def 						UpperCamelCase__					(     cls ):
       super().setUpClass()
       torch.use_deterministic_algorithms(_UpperCAmelCase )



 @classmethod
 def 						UpperCamelCase__					(     cls ):
       super().tearDownClass()
       torch.use_deterministic_algorithms(_UpperCAmelCase )



 def 						UpperCamelCase__					(     self ):
       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=_UpperCAmelCase		,				)
       snake_case_	=				DDIMScheduler(
           beta_start=0.00_085		,				beta_end=0.012		,				beta_schedule='''scaled_linear'''		,				clip_sample=_UpperCAmelCase		,				set_alpha_to_one=_UpperCAmelCase		,				)
       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=1_28		,				)
       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=10_00		,				hidden_act='''gelu'''		,				projection_dim=5_12		,				)
       snake_case_	=				CLIPTextModel(_UpperCAmelCase )
       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 						UpperCamelCase__					(     self		,				_UpperCAmelCase		,				_UpperCAmelCase=0 ):
       if str(_UpperCAmelCase ).startswith('''mps''' ):
             snake_case_	=				torch.manual_seed(_UpperCAmelCase )
       else:
             snake_case_	=				torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase )
       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 						UpperCamelCase__					(     self ):
       snake_case_	=				'''cpu'''

       snake_case_	=				self.get_dummy_components()
       snake_case_	=				self.pipeline_class(**_UpperCAmelCase )
       pipe.to(_UpperCAmelCase )
       pipe.set_progress_bar_config(disable=_UpperCAmelCase )

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

       self.assertEqual(image.shape		,				(1, 64, 64, 3) )
       snake_case_	=				np.array(
           [0.63_905_364, 0.62_897_307, 0.48_599_017, 0.5_133_624, 0.5_550_048, 0.45_769_516, 0.50_326_973, 0.5_023_139, 0.45_384_496] )
       snake_case_	=				np.abs(image_slice.flatten() - expected_slice ).max()
       self.assertLessEqual(_UpperCAmelCase		,				1E-3 )



 def 						UpperCamelCase__					(     self ):
       super().test_cpu_offload_forward_pass(expected_max_diff=5E-4 )



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



 def 						UpperCamelCase__					(     self ):
       self._test_inference_batch_single_identical(batch_size=2		,				expected_max_diff=7E-4 )



 def 						UpperCamelCase__					(     self ):
       super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 )



 def 						UpperCamelCase__					(     self ):
       super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4 )



 def 						UpperCamelCase__					(     self ):
       super().test_save_load_local(expected_max_difference=5E-4 )





 def 						UpperCamelCase__					(     self ):
       super().test_save_load_optional_components(expected_max_difference=4E-4 )







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

 '''simple docstring'''

 @classmethod
 def 						UpperCamelCase__					(     cls ):
       super().setUpClass()
       torch.use_deterministic_algorithms(_UpperCAmelCase )



 @classmethod
 def 						UpperCamelCase__					(     cls ):
       super().tearDownClass()
       torch.use_deterministic_algorithms(_UpperCAmelCase )



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





 def 						UpperCamelCase__					(     self ):
       snake_case_	=				torch.manual_seed(51 )

       snake_case_	=				StableDiffusionAttendAndExcitePipeline.from_pretrained(
           '''CompVis/stable-diffusion-v1-4'''		,				safety_checker=_UpperCAmelCase		,				torch_dtype=torch.floataa )
       pipe.to('''cuda''' )

       snake_case_	=				'''a painting of an elephant with glasses'''
       snake_case_	=				[5, 7]

       snake_case_	=				pipe(
           prompt=_UpperCAmelCase		,				token_indices=_UpperCAmelCase		,				guidance_scale=7.5		,				generator=_UpperCAmelCase		,				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



from __future__ import annotations

import time

UpperCAmelCase      =   list[tuple[int, int]]

UpperCAmelCase      =   [
    [0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 0, 0, 0],  # 0 are free path whereas 1's are obstacles
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0],
    [1, 0, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0],
]

UpperCAmelCase      =   [[-1, 0], [0, -1], [1, 0], [0, 1]]  # up, left, down, right







class lowerCAmelCase_						:

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase		,				_UpperCAmelCase		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       snake_case_	=				pos_x
       snake_case_	=				pos_y
       snake_case_	=				(pos_y, pos_x)
       snake_case_	=				goal_x
       snake_case_	=				goal_y
       snake_case_	=				parent







class lowerCAmelCase_						:

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       snake_case_	=				Node(start[1]		,				start[0]		,				goal[1]		,				goal[0]		,				_UpperCAmelCase )
       snake_case_	=				Node(goal[1]		,				goal[0]		,				goal[1]		,				goal[0]		,				_UpperCAmelCase )

       snake_case_	=				[self.start]
       snake_case_	=				False



 def 						UpperCamelCase__					(     self ):
       while self.node_queue:
             snake_case_	=				self.node_queue.pop(0 )

             if current_node.pos == self.target.pos:
                   snake_case_	=				True
                   return self.retrace_path(_UpperCAmelCase )

             snake_case_	=				self.get_successors(_UpperCAmelCase )

             for node in successors:
                   self.node_queue.append(_UpperCAmelCase )

       if not self.reached:
             return [self.start.pos]
       return None



 def 						UpperCamelCase__					(     self		,				_UpperCAmelCase ):
       snake_case_	=				[]
       for action in delta:
             snake_case_	=				parent.pos_x + action[1]
             snake_case_	=				parent.pos_y + action[0]
             if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_UpperCAmelCase ) - 1):
                   continue

             if grid[pos_y][pos_x] != 0:
                   continue

             successors.append(
                 Node(_UpperCAmelCase		,				_UpperCAmelCase		,				self.target.pos_y		,				self.target.pos_x		,				_UpperCAmelCase ) )
       return successors





 def 						UpperCamelCase__					(     self		,				_UpperCAmelCase ):
       snake_case_	=				node
       snake_case_	=				[]
       while current_node is not None:
             path.append((current_node.pos_y, current_node.pos_x) )
             snake_case_	=				current_node.parent
       path.reverse()
       return path







class lowerCAmelCase_						:

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       snake_case_	=				BreadthFirstSearch(_UpperCAmelCase		,				_UpperCAmelCase )
       snake_case_	=				BreadthFirstSearch(_UpperCAmelCase		,				_UpperCAmelCase )
       snake_case_	=				False



 def 						UpperCamelCase__					(     self ):
       while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
             snake_case_	=				self.fwd_bfs.node_queue.pop(0 )
             snake_case_	=				self.bwd_bfs.node_queue.pop(0 )

             if current_bwd_node.pos == current_fwd_node.pos:
                   snake_case_	=				True
                   return self.retrace_bidirectional_path(
                       _UpperCAmelCase		,				_UpperCAmelCase )

             snake_case_	=				current_bwd_node
             snake_case_	=				current_fwd_node

             snake_case_	=				{
                 self.fwd_bfs: self.fwd_bfs.get_successors(_UpperCAmelCase ),
                 self.bwd_bfs: self.bwd_bfs.get_successors(_UpperCAmelCase ),
             }

             for bfs in [self.fwd_bfs, self.bwd_bfs]:
                   for node in successors[bfs]:
                         bfs.node_queue.append(_UpperCAmelCase )

       if not self.reached:
             return [self.fwd_bfs.start.pos]
       return None





 def 						UpperCamelCase__					(     self		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       snake_case_	=				self.fwd_bfs.retrace_path(_UpperCAmelCase )
       snake_case_	=				self.bwd_bfs.retrace_path(_UpperCAmelCase )
       bwd_path.pop()
       bwd_path.reverse()
       snake_case_	=				fwd_path + bwd_path
       return path


if __name__ == "__main__":
   # all coordinates are given in format [y,x]
   import doctest

   doctest.testmod()
   UpperCAmelCase      =   (0, 0)
   UpperCAmelCase      =   (len(grid) - 1, len(grid[0]) - 1)
   for elem in grid:
      print(elem)

   UpperCAmelCase      =   time.time()
   UpperCAmelCase      =   BreadthFirstSearch(init, goal)
   UpperCAmelCase      =   bfs.search()
   UpperCAmelCase      =   time.time() - start_bfs_time

   print("""Unidirectional BFS computation time : """, bfs_time)

   UpperCAmelCase      =   time.time()
   UpperCAmelCase      =   BidirectionalBreadthFirstSearch(init, goal)
   UpperCAmelCase      =   bd_bfs.search()
   UpperCAmelCase      =   time.time() - start_bd_bfs_time

   print("""Bidirectional BFS computation time : """, bd_bfs_time)