


'''simple docstring'''






import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    PNDMScheduler,
    StableDiffusionLDMaDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import nightly, 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


enable_full_determinism()




class 	a__       (							unittest.TestCase						):





							'''simple docstring'''






							lowercase__    :     List[Any]					=   StableDiffusionLDMaDPipeline
							lowercase__    :     Any					=   TEXT_TO_IMAGE_PARAMS
							lowercase__    :     Optional[int]					=   TEXT_TO_IMAGE_BATCH_PARAMS
							lowercase__    :     Union[str, Any]					=   TEXT_TO_IMAGE_IMAGE_PARAMS







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							str:
														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__      =			DDIMScheduler(
														    beta_start=0.00_085      ,					beta_end=0.012      ,					beta_schedule='''scaled_linear'''      ,					clip_sample=lowerCamelCase_      ,					set_alpha_to_one=lowerCamelCase_      ,					)
														torch.manual_seed(0     )
														lowerCAmelCase__      =			AutoencoderKL(
														    block_out_channels=[32, 64]      ,					in_channels=6      ,					out_channels=6      ,					down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']      ,					up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']      ,					latent_channels=4      ,					)
														torch.manual_seed(0     )
														lowerCAmelCase__      =			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      ,					)
														lowerCAmelCase__      =			CLIPTextModel(lowerCamelCase_     )
														lowerCAmelCase__      =			CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''     )

														lowerCAmelCase__      =			{
														    '''unet''': unet,
														    '''scheduler''': scheduler,
														    '''vae''': vae,
														    '''text_encoder''': text_encoder,
														    '''tokenizer''': tokenizer,
														    '''safety_checker''': None,
														    '''feature_extractor''': None,
														}
														return components







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_      ,					lowerCamelCase_=0     ) ->							Dict:
														if str(lowerCamelCase_     ).startswith('''mps'''     ):
																					lowerCAmelCase__      =			torch.manual_seed(lowerCamelCase_     )
														else:
																					lowerCAmelCase__      =			torch.Generator(device=lowerCamelCase_     ).manual_seed(lowerCamelCase_     )
														lowerCAmelCase__      =			{
														    '''prompt''': '''A painting of a squirrel eating a burger''',
														    '''generator''': generator,
														    '''num_inference_steps''': 2,
														    '''guidance_scale''': 6.0,
														    '''output_type''': '''numpy''',
														}
														return inputs







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							int:
														lowerCAmelCase__      =			'''cpu'''  # ensure determinism for the device-dependent torch.Generator

														lowerCAmelCase__      =			self.get_dummy_components()
														lowerCAmelCase__      =			StableDiffusionLDMaDPipeline(**lowerCamelCase_     )
														lowerCAmelCase__      =			ldmad_pipe.to(lowerCamelCase_     )
														ldmad_pipe.set_progress_bar_config(disable=lowerCamelCase_     )

														lowerCAmelCase__      =			self.get_dummy_inputs(lowerCamelCase_     )
														lowerCAmelCase__      =			ldmad_pipe(**lowerCamelCase_     )
														lowerCAmelCase__     ,      lowerCAmelCase__      =			output.rgb, output.depth

														lowerCAmelCase__      =			rgb[0, -3:, -3:, -1]
														lowerCAmelCase__      =			depth[0, -3:, -1]

														assert rgb.shape == (1, 64, 64, 3)
														assert depth.shape == (1, 64, 64)

														lowerCAmelCase__      =			np.array(
														    [0.37_338_176, 0.70_247, 0.74_203_193, 0.51_643_604, 0.58_256_793, 0.60_932_136, 0.4_181_095, 0.48_355_877, 0.46_535_262]     )
														lowerCAmelCase__      =			np.array([103.46_727, 85.812_004, 87.849_236]     )

														assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb     ).max() < 1e-2
														assert np.abs(image_slice_depth.flatten() - expected_slice_depth     ).max() < 1e-2







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Union[str, Any]:
														lowerCAmelCase__      =			self.get_dummy_components()
														lowerCAmelCase__      =			StableDiffusionLDMaDPipeline(**lowerCamelCase_     )
														lowerCAmelCase__      =			ldmad_pipe.to(lowerCamelCase_     )
														ldmad_pipe.set_progress_bar_config(disable=lowerCamelCase_     )

														lowerCAmelCase__      =			self.get_dummy_inputs(lowerCamelCase_     )
														lowerCAmelCase__      =			3 * [inputs['''prompt''']]

														# forward
														lowerCAmelCase__      =			ldmad_pipe(**lowerCamelCase_     )
														lowerCAmelCase__     ,      lowerCAmelCase__      =			output.rgb, output.depth
														lowerCAmelCase__      =			rgb_slice_a[0, -3:, -3:, -1]
														lowerCAmelCase__      =			depth_slice_a[0, -3:, -1]

														lowerCAmelCase__      =			self.get_dummy_inputs(lowerCamelCase_     )
														lowerCAmelCase__      =			3 * [inputs.pop('''prompt'''     )]

														lowerCAmelCase__      =			ldmad_pipe.tokenizer(
														    lowerCamelCase_      ,					padding='''max_length'''      ,					max_length=ldmad_pipe.tokenizer.model_max_length      ,					truncation=lowerCamelCase_      ,					return_tensors='''pt'''      ,					)
														lowerCAmelCase__      =			text_inputs['''input_ids'''].to(lowerCamelCase_     )

														lowerCAmelCase__      =			ldmad_pipe.text_encoder(lowerCamelCase_     )[0]

														lowerCAmelCase__      =			prompt_embeds

														# forward
														lowerCAmelCase__      =			ldmad_pipe(**lowerCamelCase_     )
														lowerCAmelCase__     ,      lowerCAmelCase__      =			output.rgb, output.depth
														lowerCAmelCase__      =			rgb_slice_a[0, -3:, -3:, -1]
														lowerCAmelCase__      =			depth_slice_a[0, -3:, -1]

														assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten()     ).max() < 1e-4
														assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten()     ).max() < 1e-4







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Optional[Any]:
														lowerCAmelCase__      =			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
														lowerCAmelCase__      =			self.get_dummy_components()
														lowerCAmelCase__      =			PNDMScheduler(skip_prk_steps=lowerCamelCase_     )
														lowerCAmelCase__      =			StableDiffusionLDMaDPipeline(**lowerCamelCase_     )
														lowerCAmelCase__      =			ldmad_pipe.to(lowerCamelCase_     )
														ldmad_pipe.set_progress_bar_config(disable=lowerCamelCase_     )

														lowerCAmelCase__      =			self.get_dummy_inputs(lowerCamelCase_     )
														lowerCAmelCase__      =			'''french fries'''
														lowerCAmelCase__      =			ldmad_pipe(**lowerCamelCase_      ,					negative_prompt=lowerCamelCase_     )

														lowerCAmelCase__     ,      lowerCAmelCase__      =			output.rgb, output.depth
														lowerCAmelCase__      =			rgb[0, -3:, -3:, -1]
														lowerCAmelCase__      =			depth[0, -3:, -1]

														assert rgb.shape == (1, 64, 64, 3)
														assert depth.shape == (1, 64, 64)

														lowerCAmelCase__      =			np.array(
														    [0.37_044, 0.71_811_503, 0.7_223_251, 0.48_603_675, 0.5_638_391, 0.6_364_948, 0.42_833_704, 0.4_901_315, 0.47_926_217]     )
														lowerCAmelCase__      =			np.array([107.84_738, 84.62_802, 89.962_135]     )
														assert np.abs(rgb_slice.flatten() - expected_slice_rgb     ).max() < 1e-2
														assert np.abs(depth_slice.flatten() - expected_slice_depth     ).max() < 1e-2




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





							'''simple docstring'''






							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Union[str, Any]:
														super().tearDown()
														gc.collect()
														torch.cuda.empty_cache()







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_      ,					lowerCamelCase_="cpu"      ,					lowerCamelCase_=torch.floataa      ,					lowerCamelCase_=0     ) ->							int:
														lowerCAmelCase__      =			torch.Generator(device=lowerCamelCase_     ).manual_seed(lowerCamelCase_     )
														lowerCAmelCase__      =			np.random.RandomState(lowerCamelCase_     ).standard_normal((1, 4, 64, 64)     )
														lowerCAmelCase__      =			torch.from_numpy(lowerCamelCase_     ).to(device=lowerCamelCase_      ,					dtype=lowerCamelCase_     )
														lowerCAmelCase__      =			{
														    '''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     ) ->							List[Any]:
														lowerCAmelCase__      =			StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d'''     )
														lowerCAmelCase__      =			ldmad_pipe.to(lowerCamelCase_     )
														ldmad_pipe.set_progress_bar_config(disable=lowerCamelCase_     )

														lowerCAmelCase__      =			self.get_inputs(lowerCamelCase_     )
														lowerCAmelCase__      =			ldmad_pipe(**lowerCamelCase_     )
														lowerCAmelCase__     ,      lowerCAmelCase__      =			output.rgb, output.depth
														lowerCAmelCase__      =			rgb[0, -3:, -3:, -1].flatten()
														lowerCAmelCase__      =			rgb[0, -3:, -1].flatten()

														assert rgb.shape == (1, 5_12, 5_12, 3)
														assert depth.shape == (1, 5_12, 5_12)

														lowerCAmelCase__      =			np.array(
														    [0.53_805_465, 0.56_707_305, 0.5_486_515, 0.57_012_236, 0.5_814_511, 0.56_253_487, 0.54_843_014, 0.55_092_263, 0.6_459_706]     )
														lowerCAmelCase__      =			np.array(
														    [0.9_263_781, 0.6_678_672, 0.5_486_515, 0.92_202_145, 0.67_831_135, 0.56_253_487, 0.9_241_694, 0.7_551_478, 0.6_459_706]     )
														assert np.abs(rgb_slice - expected_slice_rgb     ).max() < 3e-3
														assert np.abs(depth_slice - expected_slice_depth     ).max() < 3e-3




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





							'''simple docstring'''






							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							int:
														super().tearDown()
														gc.collect()
														torch.cuda.empty_cache()







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_      ,					lowerCamelCase_="cpu"      ,					lowerCamelCase_=torch.floataa      ,					lowerCamelCase_=0     ) ->							Dict:
														lowerCAmelCase__      =			torch.Generator(device=lowerCamelCase_     ).manual_seed(lowerCamelCase_     )
														lowerCAmelCase__      =			np.random.RandomState(lowerCamelCase_     ).standard_normal((1, 4, 64, 64)     )
														lowerCAmelCase__      =			torch.from_numpy(lowerCamelCase_     ).to(device=lowerCamelCase_      ,					dtype=lowerCamelCase_     )
														lowerCAmelCase__      =			{
														    '''prompt''': '''a photograph of an astronaut riding a horse''',
														    '''latents''': latents,
														    '''generator''': generator,
														    '''num_inference_steps''': 50,
														    '''guidance_scale''': 7.5,
														    '''output_type''': '''numpy''',
														}
														return inputs







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Dict:
														lowerCAmelCase__      =			StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d'''     ).to(lowerCamelCase_     )
														ldmad_pipe.set_progress_bar_config(disable=lowerCamelCase_     )

														lowerCAmelCase__      =			self.get_inputs(lowerCamelCase_     )
														lowerCAmelCase__      =			ldmad_pipe(**lowerCamelCase_     )
														lowerCAmelCase__     ,      lowerCAmelCase__      =			output.rgb, output.depth

														lowerCAmelCase__      =			0.495_586
														lowerCAmelCase__      =			0.33_795_515
														lowerCAmelCase__      =			112.48_518
														lowerCAmelCase__      =			98.489_746
														assert np.abs(expected_rgb_mean - rgb.mean()     ) < 1e-3
														assert np.abs(expected_rgb_std - rgb.std()     ) < 1e-3
														assert np.abs(expected_depth_mean - depth.mean()     ) < 1e-3
														assert np.abs(expected_depth_std - depth.std()     ) < 1e-3







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Optional[int]:
														lowerCAmelCase__      =			StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d-4c'''     ).to(lowerCamelCase_     )
														ldmad_pipe.set_progress_bar_config(disable=lowerCamelCase_     )

														lowerCAmelCase__      =			self.get_inputs(lowerCamelCase_     )
														lowerCAmelCase__      =			ldmad_pipe(**lowerCamelCase_     )
														lowerCAmelCase__     ,      lowerCAmelCase__      =			output.rgb, output.depth

														lowerCAmelCase__      =			0.4_194_127
														lowerCAmelCase__      =			0.35_375_586
														lowerCAmelCase__      =			0.5_638_502
														lowerCAmelCase__      =			0.34_686_103

														assert rgb.shape == (1, 5_12, 5_12, 3)
														assert depth.shape == (1, 5_12, 5_12, 1)
														assert np.abs(expected_rgb_mean - rgb.mean()     ) < 1e-3
														assert np.abs(expected_rgb_std - rgb.std()     ) < 1e-3
														assert np.abs(expected_depth_mean - depth.mean()     ) < 1e-3
														assert np.abs(expected_depth_std - depth.std()     ) < 1e-3



'''simple docstring'''






from math import pi, sqrt, tan


def       _snake_case     (  A )		->					float:
							if side_length < 0:
														raise ValueError('''surface_area_cube() only accepts non-negative values''' )
							return 6 * side_length**2


def       _snake_case     (  A				,					A				,					A )		->					float:
							if length < 0 or breadth < 0 or height < 0:
														raise ValueError('''surface_area_cuboid() only accepts non-negative values''' )
							return 2 * ((length * breadth) + (breadth * height) + (length * height))


def       _snake_case     (  A )		->					float:
							if radius < 0:
														raise ValueError('''surface_area_sphere() only accepts non-negative values''' )
							return 4 * pi * radius**2


def       _snake_case     (  A )		->					float:
							if radius < 0:
														raise ValueError('''surface_area_hemisphere() only accepts non-negative values''' )
							return 3 * pi * radius**2


def       _snake_case     (  A				,					A )		->					float:
							if radius < 0 or height < 0:
														raise ValueError('''surface_area_cone() only accepts non-negative values''' )
							return pi * radius * (radius + (height**2 + radius**2) ** 0.5)


def       _snake_case     (  A				,					A				,					A )		->					float:
							if radius_a < 0 or radius_a < 0 or height < 0:
														raise ValueError(
														    '''surface_area_conical_frustum() only accepts non-negative values''' )
							lowerCAmelCase__      =			(height**2 + (radius_a - radius_a) ** 2) ** 0.5
							return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2)


def       _snake_case     (  A				,					A )		->					float:
							if radius < 0 or height < 0:
														raise ValueError('''surface_area_cylinder() only accepts non-negative values''' )
							return 2 * pi * radius * (height + radius)


def       _snake_case     (  A				,					A )		->					float:
							if torus_radius < 0 or tube_radius < 0:
														raise ValueError('''surface_area_torus() only accepts non-negative values''' )
							if torus_radius < tube_radius:
														raise ValueError(
														    '''surface_area_torus() does not support spindle or self intersecting tori''' )
							return 4 * pow(A				,					2 ) * torus_radius * tube_radius


def       _snake_case     (  A				,					A )		->					float:
							if length < 0 or width < 0:
														raise ValueError('''area_rectangle() only accepts non-negative values''' )
							return length * width


def       _snake_case     (  A )		->					float:
							if side_length < 0:
														raise ValueError('''area_square() only accepts non-negative values''' )
							return side_length**2


def       _snake_case     (  A				,					A )		->					float:
							if base < 0 or height < 0:
														raise ValueError('''area_triangle() only accepts non-negative values''' )
							return (base * height) / 2


def       _snake_case     (  A				,					A				,					A )		->					float:
							if sidea < 0 or sidea < 0 or sidea < 0:
														raise ValueError('''area_triangle_three_sides() only accepts non-negative values''' )
							elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea:
														raise ValueError('''Given three sides do not form a triangle''' )
							lowerCAmelCase__      =			(sidea + sidea + sidea) / 2
							lowerCAmelCase__      =			sqrt(
							    semi_perimeter
							    * (semi_perimeter - sidea)
							    * (semi_perimeter - sidea)
							    * (semi_perimeter - sidea) )
							return area


def       _snake_case     (  A				,					A )		->					float:
							if base < 0 or height < 0:
														raise ValueError('''area_parallelogram() only accepts non-negative values''' )
							return base * height


def       _snake_case     (  A				,					A				,					A )		->					float:
							if basea < 0 or basea < 0 or height < 0:
														raise ValueError('''area_trapezium() only accepts non-negative values''' )
							return 1 / 2 * (basea + basea) * height


def       _snake_case     (  A )		->					float:
							if radius < 0:
														raise ValueError('''area_circle() only accepts non-negative values''' )
							return pi * radius**2


def       _snake_case     (  A				,					A )		->					float:
							if radius_x < 0 or radius_y < 0:
														raise ValueError('''area_ellipse() only accepts non-negative values''' )
							return pi * radius_x * radius_y


def       _snake_case     (  A				,					A )		->					float:
							if diagonal_a < 0 or diagonal_a < 0:
														raise ValueError('''area_rhombus() only accepts non-negative values''' )
							return 1 / 2 * diagonal_a * diagonal_a


def       _snake_case     (  A				,					A )		->					float:
							if not isinstance(A				,					A ) or sides < 3:
														raise ValueError(
														    '''area_reg_polygon() only accepts integers greater than or \
equal to three as number of sides''' )
							elif length < 0:
														raise ValueError(
														    '''area_reg_polygon() only accepts non-negative values as \
length of a side''' )
							return (sides * length**2) / (4 * tan(pi / sides ))
							return (sides * length**2) / (4 * tan(pi / sides ))


if __name__ == "__main__":
		import doctest

		doctest.testmod(verbose=True)  # verbose so we can see methods missing tests

		print('''[DEMO] Areas of various geometric shapes: \n''')
		print(f"""Rectangle: {area_rectangle(10, 20) = }""")
		print(f"""Square: {area_square(10) = }""")
		print(f"""Triangle: {area_triangle(10, 10) = }""")
		print(f"""Triangle: {area_triangle_three_sides(5, 12, 13) = }""")
		print(f"""Parallelogram: {area_parallelogram(10, 20) = }""")
		print(f"""Rhombus: {area_rhombus(10, 20) = }""")
		print(f"""Trapezium: {area_trapezium(10, 20, 30) = }""")
		print(f"""Circle: {area_circle(20) = }""")
		print(f"""Ellipse: {area_ellipse(10, 20) = }""")
		print('''\nSurface Areas of various geometric shapes: \n''')
		print(f"""Cube: {surface_area_cube(20) = }""")
		print(f"""Cuboid: {surface_area_cuboid(10, 20, 30) = }""")
		print(f"""Sphere: {surface_area_sphere(20) = }""")
		print(f"""Hemisphere: {surface_area_hemisphere(20) = }""")
		print(f"""Cone: {surface_area_cone(10, 20) = }""")
		print(f"""Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }""")
		print(f"""Cylinder: {surface_area_cylinder(10, 20) = }""")
		print(f"""Torus: {surface_area_torus(20, 10) = }""")
		print(f"""Equilateral Triangle: {area_reg_polygon(3, 10) = }""")
		print(f"""Square: {area_reg_polygon(4, 10) = }""")
		print(f"""Reqular Pentagon: {area_reg_polygon(5, 10) = }""")