


'''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 		_snake_case       (  unittest.TestCase						):
					lowerCAmelCase   :Dict				=       StableDiffusionLDMaDPipeline
					lowerCAmelCase   :str				=       TEXT_TO_IMAGE_PARAMS
					lowerCAmelCase   :str				=       TEXT_TO_IMAGE_BATCH_PARAMS
					lowerCAmelCase   :List[str]				=       TEXT_TO_IMAGE_IMAGE_PARAMS




					def 					snake_case__    (   self):
								torch.manual_seed(0)
								UpperCAmelCase__	:       List[str]   =  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				,				)
								UpperCAmelCase__	:       str   =  DDIMScheduler(
								    beta_start=0.00085				,				beta_end=0.012				,				beta_schedule="""scaled_linear"""				,				clip_sample=__lowerCamelCase				,				set_alpha_to_one=__lowerCamelCase				,				)
								torch.manual_seed(0)
								UpperCAmelCase__	:       Dict   =  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)
								UpperCAmelCase__	:       List[Any]   =  CLIPTextConfig(
								    bos_token_id=0				,				eos_token_id=2				,				hidden_size=32				,				intermediate_size=37				,				layer_norm_eps=1e-0_5				,				num_attention_heads=4				,				num_hidden_layers=5				,				pad_token_id=1				,				vocab_size=1000				,				)
								UpperCAmelCase__	:       List[Any]   =  CLIPTextModel(__lowerCamelCase)
								UpperCAmelCase__	:       Optional[Any]   =  CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")

								UpperCAmelCase__	:       Dict   =  {
								    """unet""": unet,
								    """scheduler""": scheduler,
								    """vae""": vae,
								    """text_encoder""": text_encoder,
								    """tokenizer""": tokenizer,
								    """safety_checker""": None,
								    """feature_extractor""": None,
								}
								return components




					def 					snake_case__    (   self				,				_lowerCamelCase				,				_lowerCamelCase=0):
								if str(__lowerCamelCase).startswith("""mps"""):
											UpperCAmelCase__	:       Union[str, Any]   =  torch.manual_seed(__lowerCamelCase)
								else:
											UpperCAmelCase__	:       int   =  torch.Generator(device=__lowerCamelCase).manual_seed(__lowerCamelCase)
								UpperCAmelCase__	:       Any   =  {
								    """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 					snake_case__    (   self):
								UpperCAmelCase__	:       str   =  """cpu"""  # ensure determinism for the device-dependent torch.Generator

								UpperCAmelCase__	:       Any   =  self.get_dummy_components()
								UpperCAmelCase__	:       Optional[Any]   =  StableDiffusionLDMaDPipeline(**__lowerCamelCase)
								UpperCAmelCase__	:       Union[str, Any]   =  ldmad_pipe.to(__lowerCamelCase)
								ldmad_pipe.set_progress_bar_config(disable=__lowerCamelCase)

								UpperCAmelCase__	:       Dict   =  self.get_dummy_inputs(__lowerCamelCase)
								UpperCAmelCase__	:       int   =  ldmad_pipe(**__lowerCamelCase)
								UpperCAmelCase__ ,							UpperCAmelCase__	:       Tuple   =  output.rgb, output.depth

								UpperCAmelCase__	:       Optional[Any]   =  rgb[0, -3:, -3:, -1]
								UpperCAmelCase__	:       List[str]   =  depth[0, -3:, -1]

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

								UpperCAmelCase__	:       int   =  np.array(
								    [0.37338176, 0.70247, 0.74203193, 0.51643604, 0.58256793, 0.60932136, 0.4181095, 0.48355877, 0.46535262])
								UpperCAmelCase__	:       str   =  np.array([103.46727, 85.812004, 87.849236])

								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 					snake_case__    (   self):
								UpperCAmelCase__	:       List[Any]   =  self.get_dummy_components()
								UpperCAmelCase__	:       Optional[int]   =  StableDiffusionLDMaDPipeline(**__lowerCamelCase)
								UpperCAmelCase__	:       Dict   =  ldmad_pipe.to(__lowerCamelCase)
								ldmad_pipe.set_progress_bar_config(disable=__lowerCamelCase)

								UpperCAmelCase__	:       int   =  self.get_dummy_inputs(__lowerCamelCase)
								UpperCAmelCase__	:       Dict   =  3 * [inputs["""prompt"""]]

								# forward
								UpperCAmelCase__	:       Optional[Any]   =  ldmad_pipe(**__lowerCamelCase)
								UpperCAmelCase__ ,							UpperCAmelCase__	:       List[Any]   =  output.rgb, output.depth
								UpperCAmelCase__	:       str   =  rgb_slice_a[0, -3:, -3:, -1]
								UpperCAmelCase__	:       List[str]   =  depth_slice_a[0, -3:, -1]

								UpperCAmelCase__	:       Optional[int]   =  self.get_dummy_inputs(__lowerCamelCase)
								UpperCAmelCase__	:       str   =  3 * [inputs.pop("""prompt""")]

								UpperCAmelCase__	:       Tuple   =  ldmad_pipe.tokenizer(
								    __lowerCamelCase				,				padding="""max_length"""				,				max_length=ldmad_pipe.tokenizer.model_max_length				,				truncation=__lowerCamelCase				,				return_tensors="""pt"""				,				)
								UpperCAmelCase__	:       str   =  text_inputs["""input_ids"""].to(__lowerCamelCase)

								UpperCAmelCase__	:       str   =  ldmad_pipe.text_encoder(__lowerCamelCase)[0]

								UpperCAmelCase__	:       Optional[int]   =  prompt_embeds

								# forward
								UpperCAmelCase__	:       List[Any]   =  ldmad_pipe(**__lowerCamelCase)
								UpperCAmelCase__ ,							UpperCAmelCase__	:       str   =  output.rgb, output.depth
								UpperCAmelCase__	:       Optional[Any]   =  rgb_slice_a[0, -3:, -3:, -1]
								UpperCAmelCase__	:       Optional[Any]   =  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 					snake_case__    (   self):
								UpperCAmelCase__	:       Tuple   =  """cpu"""  # ensure determinism for the device-dependent torch.Generator
								UpperCAmelCase__	:       Dict   =  self.get_dummy_components()
								UpperCAmelCase__	:       int   =  PNDMScheduler(skip_prk_steps=__lowerCamelCase)
								UpperCAmelCase__	:       List[str]   =  StableDiffusionLDMaDPipeline(**__lowerCamelCase)
								UpperCAmelCase__	:       Any   =  ldmad_pipe.to(__lowerCamelCase)
								ldmad_pipe.set_progress_bar_config(disable=__lowerCamelCase)

								UpperCAmelCase__	:       Optional[Any]   =  self.get_dummy_inputs(__lowerCamelCase)
								UpperCAmelCase__	:       Tuple   =  """french fries"""
								UpperCAmelCase__	:       List[Any]   =  ldmad_pipe(**__lowerCamelCase				,				negative_prompt=__lowerCamelCase)

								UpperCAmelCase__ ,							UpperCAmelCase__	:       Optional[Any]   =  output.rgb, output.depth
								UpperCAmelCase__	:       Optional[int]   =  rgb[0, -3:, -3:, -1]
								UpperCAmelCase__	:       Tuple   =  depth[0, -3:, -1]

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

								UpperCAmelCase__	:       str   =  np.array(
								    [0.37044, 0.71811503, 0.7223251, 0.48603675, 0.5638391, 0.6364948, 0.42833704, 0.4901315, 0.47926217])
								UpperCAmelCase__	:       Tuple   =  np.array([107.84738, 84.62802, 89.962135])
								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 		_snake_case       (  unittest.TestCase						):




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




					def 					snake_case__    (   self				,				_lowerCamelCase				,				_lowerCamelCase="cpu"				,				_lowerCamelCase=torch.floataa				,				_lowerCamelCase=0):
								UpperCAmelCase__	:       Tuple   =  torch.Generator(device=__lowerCamelCase).manual_seed(__lowerCamelCase)
								UpperCAmelCase__	:       Tuple   =  np.random.RandomState(__lowerCamelCase).standard_normal((1, 4, 64, 64))
								UpperCAmelCase__	:       int   =  torch.from_numpy(__lowerCamelCase).to(device=__lowerCamelCase				,				dtype=__lowerCamelCase)
								UpperCAmelCase__	:       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 					snake_case__    (   self):
								UpperCAmelCase__	:       Any   =  StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d""")
								UpperCAmelCase__	:       int   =  ldmad_pipe.to(__lowerCamelCase)
								ldmad_pipe.set_progress_bar_config(disable=__lowerCamelCase)

								UpperCAmelCase__	:       Optional[int]   =  self.get_inputs(__lowerCamelCase)
								UpperCAmelCase__	:       List[Any]   =  ldmad_pipe(**__lowerCamelCase)
								UpperCAmelCase__ ,							UpperCAmelCase__	:       Optional[Any]   =  output.rgb, output.depth
								UpperCAmelCase__	:       Optional[Any]   =  rgb[0, -3:, -3:, -1].flatten()
								UpperCAmelCase__	:       Dict   =  rgb[0, -3:, -1].flatten()

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

								UpperCAmelCase__	:       Union[str, Any]   =  np.array(
								    [0.53805465, 0.56707305, 0.5486515, 0.57012236, 0.5814511, 0.56253487, 0.54843014, 0.55092263, 0.6459706])
								UpperCAmelCase__	:       Optional[int]   =  np.array(
								    [0.9263781, 0.6678672, 0.5486515, 0.92202145, 0.67831135, 0.56253487, 0.9241694, 0.7551478, 0.6459706])
								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 		_snake_case       (  unittest.TestCase						):




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




					def 					snake_case__    (   self				,				_lowerCamelCase				,				_lowerCamelCase="cpu"				,				_lowerCamelCase=torch.floataa				,				_lowerCamelCase=0):
								UpperCAmelCase__	:       Tuple   =  torch.Generator(device=__lowerCamelCase).manual_seed(__lowerCamelCase)
								UpperCAmelCase__	:       List[Any]   =  np.random.RandomState(__lowerCamelCase).standard_normal((1, 4, 64, 64))
								UpperCAmelCase__	:       Dict   =  torch.from_numpy(__lowerCamelCase).to(device=__lowerCamelCase				,				dtype=__lowerCamelCase)
								UpperCAmelCase__	:       Union[str, Any]   =  {
								    """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 					snake_case__    (   self):
								UpperCAmelCase__	:       Tuple   =  StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d""").to(__lowerCamelCase)
								ldmad_pipe.set_progress_bar_config(disable=__lowerCamelCase)

								UpperCAmelCase__	:       str   =  self.get_inputs(__lowerCamelCase)
								UpperCAmelCase__	:       Dict   =  ldmad_pipe(**__lowerCamelCase)
								UpperCAmelCase__ ,							UpperCAmelCase__	:       Any   =  output.rgb, output.depth

								UpperCAmelCase__	:       List[Any]   =  0.495586
								UpperCAmelCase__	:       Union[str, Any]   =  0.33795515
								UpperCAmelCase__	:       List[Any]   =  112.48518
								UpperCAmelCase__	:       Dict   =  98.489746
								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 					snake_case__    (   self):
								UpperCAmelCase__	:       Dict   =  StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d-4c""").to(__lowerCamelCase)
								ldmad_pipe.set_progress_bar_config(disable=__lowerCamelCase)

								UpperCAmelCase__	:       List[str]   =  self.get_inputs(__lowerCamelCase)
								UpperCAmelCase__	:       str   =  ldmad_pipe(**__lowerCamelCase)
								UpperCAmelCase__ ,							UpperCAmelCase__	:       str   =  output.rgb, output.depth

								UpperCAmelCase__	:       Any   =  0.4194127
								UpperCAmelCase__	:       Any   =  0.35375586
								UpperCAmelCase__	:       List[Any]   =  0.5638502
								UpperCAmelCase__	:       List[str]   =  0.34686103

								assert rgb.shape == (1, 512, 512, 3)
								assert depth.shape == (1, 512, 512, 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






from __future__ import annotations

import math
from collections.abc import Callable


def       UpperCamelCase__(			UpperCamelCase__     :			Callable[[int | float], int | float]					,	UpperCamelCase__     :			int | float					,	UpperCamelCase__     :			int | float					,	UpperCamelCase__     :			int = 1_00					,	)->float:
       A__		   =		x_start
       A__		   =		fnc(UpperCamelCase__    )
       A__		   =		0.0

       for _ in range(UpperCamelCase__    ):
              # Approximates curve as a sequence of linear lines and sums their length
              A__		   =		(x_end - x_start) / steps + xa
              A__		   =		fnc(UpperCamelCase__    )
              length += math.hypot(xa - xa					,	fxa - fxa    )

              # Increment step
              A__		   =		xa
              A__		   =		fxa

       return length


if __name__ == "__main__":


       def       UpperCamelCase__(			UpperCamelCase__     :			Union[str, Any]    )->Dict:
              return math.sin(10 * x    )

       print('f(x) = sin(10 * x)')
       print('The length of the curve from x = -10 to x = 10 is:')
       a__: str							   =						10
       while i <= 100_000:
              print(F"With {i} steps: {line_length(f, -10, 10, i)}")
              i *= 10





