
'''simple docstring'''

import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModelWithProjection

from diffusers import (
    AutoencoderKL,
    DPMSolverMultistepScheduler,
    PNDMScheduler,
    StableDiffusionImageVariationPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class    A     (	SCREAMING_SNAKE_CASE__  ,      SCREAMING_SNAKE_CASE__  ,      SCREAMING_SNAKE_CASE__  ,      unittest.TestCase    ):
 snake_case__      :Any        =     StableDiffusionImageVariationPipeline
 snake_case__      :int        =     IMAGE_VARIATION_PARAMS
 snake_case__      :List[Any]        =     IMAGE_VARIATION_BATCH_PARAMS
 snake_case__      :int        =     frozenset([]    )
 # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
 snake_case__      :Tuple        =     frozenset([]    )





 def 							__SCREAMING_SNAKE_CASE  (					self			:       Tuple							):


    """simple docstring"""

    torch.manual_seed(0							)
    lowerCAmelCase__								=							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")      ,							cross_attention_dim=32      ,							)
    lowerCAmelCase__								=							PNDMScheduler(skip_prk_steps=__magic_name__							)
    torch.manual_seed(0							)
    lowerCAmelCase__								=							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      ,							)
    torch.manual_seed(0							)
    lowerCAmelCase__								=							CLIPVisionConfig(
        hidden_size=32      ,							projection_dim=32      ,							intermediate_size=37      ,							layer_norm_eps=1E-05      ,							num_attention_heads=4      ,							num_hidden_layers=5      ,							image_size=32      ,							patch_size=4      ,							)
    lowerCAmelCase__								=							CLIPVisionModelWithProjection(__magic_name__							)
    lowerCAmelCase__								=							CLIPImageProcessor(crop_size=32      ,							size=32							)

    lowerCAmelCase__								=							{
        "unet": unet,
        "scheduler": scheduler,
        "vae": vae,
        "image_encoder": image_encoder,
        "feature_extractor": feature_extractor,
        "safety_checker": None,
    }
    return components





 def 							__SCREAMING_SNAKE_CASE  (					self			:       Tuple      ,							__magic_name__			:       Union[str, Any]      ,							__magic_name__			:       Tuple=0							):


    """simple docstring"""

    lowerCAmelCase__								=							floats_tensor((1, 3, 32, 32)      ,							rng=random.Random(__magic_name__							)							)
    lowerCAmelCase__								=							image.cpu().permute(0      ,							2      ,							3      ,							1							)[0]
    lowerCAmelCase__								=							Image.fromarray(np.uinta(__magic_name__							)							).convert("RGB"							).resize((32, 32)							)
    if str(__magic_name__							).startswith("mps"							):
       lowerCAmelCase__								=							torch.manual_seed(__magic_name__							)
    else:
       lowerCAmelCase__								=							torch.Generator(device=__magic_name__							).manual_seed(__magic_name__							)
    lowerCAmelCase__								=							{
        "image": image,
        "generator": generator,
        "num_inference_steps": 2,
        "guidance_scale": 6.0,
        "output_type": "numpy",
    }
    return inputs





 def 							__SCREAMING_SNAKE_CASE  (					self			:       List[str]							):


    """simple docstring"""

    lowerCAmelCase__								=							"cpu"  # ensure determinism for the device-dependent torch.Generator
    lowerCAmelCase__								=							self.get_dummy_components()
    lowerCAmelCase__								=							StableDiffusionImageVariationPipeline(**__magic_name__							)
    lowerCAmelCase__								=							sd_pipe.to(__magic_name__							)
    sd_pipe.set_progress_bar_config(disable=__magic_name__							)

    lowerCAmelCase__								=							self.get_dummy_inputs(__magic_name__							)
    lowerCAmelCase__								=							sd_pipe(**__magic_name__							).images
    lowerCAmelCase__								=							image[0, -3:, -3:, -1]

    assert image.shape == (1, 64, 64, 3)
    lowerCAmelCase__								=							np.array([0.5239, 0.5723, 0.4796, 0.5049, 0.5550, 0.4685, 0.5329, 0.4891, 0.4921]							)

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





 def 							__SCREAMING_SNAKE_CASE  (					self			:       Dict							):


    """simple docstring"""

    lowerCAmelCase__								=							"cpu"  # ensure determinism for the device-dependent torch.Generator
    lowerCAmelCase__								=							self.get_dummy_components()
    lowerCAmelCase__								=							StableDiffusionImageVariationPipeline(**__magic_name__							)
    lowerCAmelCase__								=							sd_pipe.to(__magic_name__							)
    sd_pipe.set_progress_bar_config(disable=__magic_name__							)

    lowerCAmelCase__								=							self.get_dummy_inputs(__magic_name__							)
    lowerCAmelCase__								=							2 * [inputs["image"]]
    lowerCAmelCase__								=							sd_pipe(**__magic_name__							)

    lowerCAmelCase__								=							output.images

    lowerCAmelCase__								=							image[-1, -3:, -3:, -1]

    assert image.shape == (2, 64, 64, 3)
    lowerCAmelCase__								=							np.array([0.6892, 0.5637, 0.5836, 0.5771, 0.6254, 0.6409, 0.5580, 0.5569, 0.5289]							)

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







 def 							__SCREAMING_SNAKE_CASE  (					self			:       Optional[Any]							):


    """simple docstring"""

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






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





 def 							__SCREAMING_SNAKE_CASE  (					self			:       int							):


    """simple docstring"""

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





 def 							__SCREAMING_SNAKE_CASE  (					self			:       Any      ,							__magic_name__			:       int      ,							__magic_name__			:       Optional[Any]="cpu"      ,							__magic_name__			:       Optional[Any]=torch.floataa      ,							__magic_name__			:       str=0							):


    """simple docstring"""

    lowerCAmelCase__								=							torch.Generator(device=__magic_name__							).manual_seed(__magic_name__							)
    lowerCAmelCase__								=							load_image(
        "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
        "/stable_diffusion_imgvar/input_image_vermeer.png"							)
    lowerCAmelCase__								=							np.random.RandomState(__magic_name__							).standard_normal((1, 4, 64, 64)							)
    lowerCAmelCase__								=							torch.from_numpy(__magic_name__							).to(device=__magic_name__      ,							dtype=__magic_name__							)
    lowerCAmelCase__								=							{
        "image": init_image,
        "latents": latents,
        "generator": generator,
        "num_inference_steps": 3,
        "guidance_scale": 7.5,
        "output_type": "numpy",
    }
    return inputs





 def 							__SCREAMING_SNAKE_CASE  (					self			:       Optional[Any]							):


    """simple docstring"""

    lowerCAmelCase__								=							StableDiffusionImageVariationPipeline.from_pretrained(
        "lambdalabs/sd-image-variations-diffusers"      ,							safety_checker=__magic_name__							)
    lowerCAmelCase__								=							sd_pipe.to(__magic_name__							)
    sd_pipe.set_progress_bar_config(disable=__magic_name__							)

    lowerCAmelCase__								=							self.get_inputs(__magic_name__							)
    lowerCAmelCase__								=							sd_pipe(**__magic_name__							).images
    lowerCAmelCase__								=							image[0, -3:, -3:, -1].flatten()

    assert image.shape == (1, 512, 512, 3)
    lowerCAmelCase__								=							np.array([0.8_4491, 0.9_0789, 0.7_5708, 0.7_8734, 0.8_3485, 0.7_0099, 0.6_6938, 0.6_8727, 0.6_1379]							)
    assert np.abs(image_slice - expected_slice							).max() < 6E-3





 def 							__SCREAMING_SNAKE_CASE  (					self			:       Any							):


    """simple docstring"""

    lowerCAmelCase__								=							0

    def callback_fn(__magic_name__			:       int      ,							__magic_name__			:       int      ,							__magic_name__			:       torch.FloatTensor							) -> None:
       lowerCAmelCase__								=							True
       nonlocal number_of_steps
       number_of_steps += 1
       if step == 1:
          lowerCAmelCase__								=							latents.detach().cpu().numpy()
          assert latents.shape == (1, 4, 64, 64)
          lowerCAmelCase__								=							latents[0, -3:, -3:, -1]
          lowerCAmelCase__								=							np.array(
              [-0.1621, 0.2837, -0.7979, -0.1221, -1.3057, 0.7681, -2.1191, 0.0464, 1.6309]							)

          assert np.abs(latents_slice.flatten() - expected_slice							).max() < 5E-2
       elif step == 2:
          lowerCAmelCase__								=							latents.detach().cpu().numpy()
          assert latents.shape == (1, 4, 64, 64)
          lowerCAmelCase__								=							latents[0, -3:, -3:, -1]
          lowerCAmelCase__								=							np.array([0.6299, 1.7500, 1.1992, -2.1582, -1.8994, 0.7334, -0.7090, 1.0137, 1.5273]							)

          assert np.abs(latents_slice.flatten() - expected_slice							).max() < 5E-2

    lowerCAmelCase__								=							False

    lowerCAmelCase__								=							StableDiffusionImageVariationPipeline.from_pretrained(
        "fusing/sd-image-variations-diffusers"      ,							safety_checker=__magic_name__      ,							torch_dtype=torch.floataa      ,							)
    pipe.to(__magic_name__							)
    pipe.set_progress_bar_config(disable=__magic_name__							)
    pipe.enable_attention_slicing()

    lowerCAmelCase__								=							self.get_inputs(__magic_name__      ,							dtype=torch.floataa							)
    pipe(**__magic_name__      ,							callback=__magic_name__      ,							callback_steps=1							)
    assert callback_fn.has_been_called
    assert number_of_steps == inputs["num_inference_steps"]







 def 							__SCREAMING_SNAKE_CASE  (					self			:       int							):


    """simple docstring"""

    torch.cuda.empty_cache()
    torch.cuda.reset_max_memory_allocated()
    torch.cuda.reset_peak_memory_stats()

    lowerCAmelCase__								=							"fusing/sd-image-variations-diffusers"
    lowerCAmelCase__								=							StableDiffusionImageVariationPipeline.from_pretrained(
        __magic_name__      ,							safety_checker=__magic_name__      ,							torch_dtype=torch.floataa							)
    lowerCAmelCase__								=							pipe.to(__magic_name__							)
    pipe.set_progress_bar_config(disable=__magic_name__							)
    pipe.enable_attention_slicing(1							)
    pipe.enable_sequential_cpu_offload()

    lowerCAmelCase__								=							self.get_inputs(__magic_name__      ,							dtype=torch.floataa							)
    lowerCAmelCase__								=							pipe(**__magic_name__							)

    lowerCAmelCase__								=							torch.cuda.max_memory_allocated()
    # make sure that less than 2.6 GB is allocated
    assert mem_bytes < 2.6 * 10**9






@nightly
@require_torch_gpu
class    A     (	unittest.TestCase    ):





 def 							__SCREAMING_SNAKE_CASE  (					self			:       Optional[int]							):


    """simple docstring"""

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





 def 							__SCREAMING_SNAKE_CASE  (					self			:       Union[str, Any]      ,							__magic_name__			:       int      ,							__magic_name__			:       Union[str, Any]="cpu"      ,							__magic_name__			:       List[str]=torch.floataa      ,							__magic_name__			:       int=0							):


    """simple docstring"""

    lowerCAmelCase__								=							torch.Generator(device=__magic_name__							).manual_seed(__magic_name__							)
    lowerCAmelCase__								=							load_image(
        "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
        "/stable_diffusion_imgvar/input_image_vermeer.png"							)
    lowerCAmelCase__								=							np.random.RandomState(__magic_name__							).standard_normal((1, 4, 64, 64)							)
    lowerCAmelCase__								=							torch.from_numpy(__magic_name__							).to(device=__magic_name__      ,							dtype=__magic_name__							)
    lowerCAmelCase__								=							{
        "image": init_image,
        "latents": latents,
        "generator": generator,
        "num_inference_steps": 50,
        "guidance_scale": 7.5,
        "output_type": "numpy",
    }
    return inputs





 def 							__SCREAMING_SNAKE_CASE  (					self			:       Optional[int]							):


    """simple docstring"""

    lowerCAmelCase__								=							StableDiffusionImageVariationPipeline.from_pretrained("fusing/sd-image-variations-diffusers"							)
    sd_pipe.to(__magic_name__							)
    sd_pipe.set_progress_bar_config(disable=__magic_name__							)

    lowerCAmelCase__								=							self.get_inputs(__magic_name__							)
    lowerCAmelCase__								=							sd_pipe(**__magic_name__							).images[0]

    lowerCAmelCase__								=							load_numpy(
        "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
        "/stable_diffusion_imgvar/lambdalabs_variations_pndm.npy"							)
    lowerCAmelCase__								=							np.abs(expected_image - image							).max()
    assert max_diff < 1E-3







 def 							__SCREAMING_SNAKE_CASE  (					self			:       Tuple							):


    """simple docstring"""

    lowerCAmelCase__								=							StableDiffusionImageVariationPipeline.from_pretrained("fusing/sd-image-variations-diffusers"							)
    lowerCAmelCase__								=							DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config							)
    sd_pipe.to(__magic_name__							)
    sd_pipe.set_progress_bar_config(disable=__magic_name__							)

    lowerCAmelCase__								=							self.get_inputs(__magic_name__							)
    lowerCAmelCase__								=							25
    lowerCAmelCase__								=							sd_pipe(**__magic_name__							).images[0]

    lowerCAmelCase__								=							load_numpy(
        "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
        "/stable_diffusion_imgvar/lambdalabs_variations_dpm_multi.npy"							)
    lowerCAmelCase__								=							np.abs(expected_image - image							).max()
    assert max_diff < 1E-3







'''simple docstring'''

def   A     (      UpperCamelCase_					:     int						,	UpperCamelCase_					:     int						,	UpperCamelCase_					:     int						,	UpperCamelCase_					:     int      )					->       int:







			'''simple docstring'''



			return len_board * len_board_column * row + column







def   A     (      UpperCamelCase_					:     list[list[str]]						,	UpperCamelCase_					:     str						,	UpperCamelCase_					:     int						,	UpperCamelCase_					:     int						,	UpperCamelCase_					:     int						,	UpperCamelCase_					:     set[int]						,	)					->       bool:







			'''simple docstring'''



			if board[row][column] != word[word_index]:
						return False

			if word_index == len(UpperCamelCase_      ) - 1:
						return True

			lowerCAmelCase__								=							[(0, 1), (0, -1), (-1, 0), (1, 0)]
			lowerCAmelCase__								=							len(UpperCamelCase_      )
			lowerCAmelCase__								=							len(board[0]      )
			for direction in traverts_directions:
						lowerCAmelCase__								=							row + direction[0]
						lowerCAmelCase__								=							column + direction[1]
						if not (0 <= next_i < len_board and 0 <= next_j < len_board_column):
									continue

						lowerCAmelCase__								=							get_point_key(UpperCamelCase_						,	UpperCamelCase_						,	UpperCamelCase_						,	UpperCamelCase_      )
						if key in visited_points_set:
									continue

						visited_points_set.add(UpperCamelCase_      )
						if exits_word(UpperCamelCase_						,	UpperCamelCase_						,	UpperCamelCase_						,	UpperCamelCase_						,	word_index + 1						,	UpperCamelCase_      ):
									return True

						visited_points_set.remove(UpperCamelCase_      )

			return False







def   A     (      UpperCamelCase_					:     list[list[str]]						,	UpperCamelCase_					:     str      )					->       bool:







			'''simple docstring'''



			lowerCAmelCase__								=							(
			    "The board should be a non empty matrix of single chars strings."
			)

			lowerCAmelCase__								=							len(UpperCamelCase_      )
			if not isinstance(UpperCamelCase_						,	UpperCamelCase_      ) or len(UpperCamelCase_      ) == 0:
						raise ValueError(UpperCamelCase_      )

			for row in board:
						if not isinstance(UpperCamelCase_						,	UpperCamelCase_      ) or len(UpperCamelCase_      ) == 0:
									raise ValueError(UpperCamelCase_      )

						for item in row:
									if not isinstance(UpperCamelCase_						,	UpperCamelCase_      ) or len(UpperCamelCase_      ) != 1:
												raise ValueError(UpperCamelCase_      )

    # Validate word
			if not isinstance(UpperCamelCase_						,	UpperCamelCase_      ) or len(UpperCamelCase_      ) == 0:
						raise ValueError(
						    "The word parameter should be a string of length greater than 0."      )

			lowerCAmelCase__								=							len(board[0]      )
			for i in range(UpperCamelCase_      ):
						for j in range(UpperCamelCase_      ):
									if exits_word(
									    UpperCamelCase_						,	UpperCamelCase_						,	UpperCamelCase_						,	UpperCamelCase_						,	0						,	{get_point_key(UpperCamelCase_						,	UpperCamelCase_						,	UpperCamelCase_						,	UpperCamelCase_      )}      ):
												return True

			return False


if __name__ == "__main__":
		import doctest

		doctest.testmod()





