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     ):
   __UpperCAmelCase : List[str]      =			StableDiffusionLDMaDPipeline
   __UpperCAmelCase : Optional[Any]      =			TEXT_TO_IMAGE_PARAMS
   __UpperCAmelCase : Optional[int]      =			TEXT_TO_IMAGE_BATCH_PARAMS
   __UpperCAmelCase : str      =			TEXT_TO_IMAGE_IMAGE_PARAMS


   def 			lowercase_      (self     :						Any		)						->				Optional[int]:
         """simple docstring"""



         torch.manual_seed(0		)
         UpperCAmelCase__								=  UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)       ,  layers_per_block=2       ,  sample_size=3_2       ,  in_channels=4       ,  out_channels=4       ,  down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")       ,  up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")       ,  cross_attention_dim=3_2       ,  )
         UpperCAmelCase__								=  DDIMScheduler(
             beta_start=0.00085       ,  beta_end=0.012       ,  beta_schedule="scaled_linear"       ,  clip_sample=__UpperCAmelCase       ,  set_alpha_to_one=__UpperCAmelCase       ,  )
         torch.manual_seed(0		)
         UpperCAmelCase__								=  AutoencoderKL(
             block_out_channels=[3_2, 6_4]       ,  in_channels=6       ,  out_channels=6       ,  down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]       ,  up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]       ,  latent_channels=4       ,  )
         torch.manual_seed(0		)
         UpperCAmelCase__								=  CLIPTextConfig(
             bos_token_id=0       ,  eos_token_id=2       ,  hidden_size=3_2       ,  intermediate_size=3_7       ,  layer_norm_eps=1E-05       ,  num_attention_heads=4       ,  num_hidden_layers=5       ,  pad_token_id=1       ,  vocab_size=1_0_0_0       ,  )
         UpperCAmelCase__								=  CLIPTextModel(__UpperCAmelCase		)
         UpperCAmelCase__								=  CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		)

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


   def 			lowercase_      (self     :						Any       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Dict=0		)						->				Optional[Any]:
         """simple docstring"""



         if str(__UpperCAmelCase		).startswith("mps"		):
               UpperCAmelCase__								=  torch.manual_seed(__UpperCAmelCase		)
         else:
               UpperCAmelCase__								=  torch.Generator(device=__UpperCAmelCase		).manual_seed(__UpperCAmelCase		)
         UpperCAmelCase__								=  {
             "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 			lowercase_      (self     :						List[str]		)						->				str:
         """simple docstring"""



         UpperCAmelCase__								=  "cpu"  # ensure determinism for the device-dependent torch.Generator

         UpperCAmelCase__								=  self.get_dummy_components()
         UpperCAmelCase__								=  StableDiffusionLDMaDPipeline(**__UpperCAmelCase		)
         UpperCAmelCase__								=  ldmad_pipe.to(__UpperCAmelCase		)
         ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

         UpperCAmelCase__								=  self.get_dummy_inputs(__UpperCAmelCase		)
         UpperCAmelCase__								=  ldmad_pipe(**__UpperCAmelCase		)
         UpperCAmelCase__		,      UpperCAmelCase__								=  output.rgb, output.depth

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

         assert rgb.shape == (1, 6_4, 6_4, 3)
         assert depth.shape == (1, 6_4, 6_4)

         UpperCAmelCase__								=  np.array(
             [0.37338176, 0.70247, 0.74203193, 0.51643604, 0.58256793, 0.60932136, 0.4181095, 0.48355877, 0.46535262]		)
         UpperCAmelCase__								=  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 			lowercase_      (self     :						int		)						->				List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  self.get_dummy_components()
         UpperCAmelCase__								=  StableDiffusionLDMaDPipeline(**__UpperCAmelCase		)
         UpperCAmelCase__								=  ldmad_pipe.to(__UpperCAmelCase		)
         ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

         UpperCAmelCase__								=  self.get_dummy_inputs(__UpperCAmelCase		)
         UpperCAmelCase__								=  3 * [inputs["prompt"]]

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

         UpperCAmelCase__								=  self.get_dummy_inputs(__UpperCAmelCase		)
         UpperCAmelCase__								=  3 * [inputs.pop("prompt"		)]

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

         UpperCAmelCase__								=  ldmad_pipe.text_encoder(__UpperCAmelCase		)[0]

         UpperCAmelCase__								=  prompt_embeds

         # forward
         UpperCAmelCase__								=  ldmad_pipe(**__UpperCAmelCase		)
         UpperCAmelCase__		,      UpperCAmelCase__								=  output.rgb, output.depth
         UpperCAmelCase__								=  rgb_slice_a[0, -3:, -3:, -1]
         UpperCAmelCase__								=  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 			lowercase_      (self     :						List[Any]		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  "cpu"  # ensure determinism for the device-dependent torch.Generator
         UpperCAmelCase__								=  self.get_dummy_components()
         UpperCAmelCase__								=  PNDMScheduler(skip_prk_steps=__UpperCAmelCase		)
         UpperCAmelCase__								=  StableDiffusionLDMaDPipeline(**__UpperCAmelCase		)
         UpperCAmelCase__								=  ldmad_pipe.to(__UpperCAmelCase		)
         ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

         UpperCAmelCase__								=  self.get_dummy_inputs(__UpperCAmelCase		)
         UpperCAmelCase__								=  "french fries"
         UpperCAmelCase__								=  ldmad_pipe(**__UpperCAmelCase       ,  negative_prompt=__UpperCAmelCase		)

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

         assert rgb.shape == (1, 6_4, 6_4, 3)
         assert depth.shape == (1, 6_4, 6_4)

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


   def 			lowercase_      (self     :						List[Any]		)						->				Union[str, Any]:
         """simple docstring"""



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


   def 			lowercase_      (self     :						Tuple       ,  __UpperCAmelCase     :						Optional[int]       ,  __UpperCAmelCase     :						Tuple="cpu"       ,  __UpperCAmelCase     :						Tuple=torch.floataa       ,  __UpperCAmelCase     :						Optional[int]=0		)						->				int:
         """simple docstring"""



         UpperCAmelCase__								=  torch.Generator(device=__UpperCAmelCase		).manual_seed(__UpperCAmelCase		)
         UpperCAmelCase__								=  np.random.RandomState(__UpperCAmelCase		).standard_normal((1, 4, 6_4, 6_4)		)
         UpperCAmelCase__								=  torch.from_numpy(__UpperCAmelCase		).to(device=__UpperCAmelCase       ,  dtype=__UpperCAmelCase		)
         UpperCAmelCase__								=  {
             "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 			lowercase_      (self     :						Tuple		)						->				Dict:
         """simple docstring"""



         UpperCAmelCase__								=  StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d"		)
         UpperCAmelCase__								=  ldmad_pipe.to(__UpperCAmelCase		)
         ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

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

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

         UpperCAmelCase__								=  np.array(
             [0.53805465, 0.56707305, 0.5486515, 0.57012236, 0.5814511, 0.56253487, 0.54843014, 0.55092263, 0.6459706]		)
         UpperCAmelCase__								=  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      A							(				unittest.TestCase     ):


   def 			lowercase_      (self     :						Union[str, Any]		)						->				Optional[Any]:
         """simple docstring"""



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


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						Optional[Any]="cpu"       ,  __UpperCAmelCase     :						Optional[int]=torch.floataa       ,  __UpperCAmelCase     :						Optional[int]=0		)						->				str:
         """simple docstring"""



         UpperCAmelCase__								=  torch.Generator(device=__UpperCAmelCase		).manual_seed(__UpperCAmelCase		)
         UpperCAmelCase__								=  np.random.RandomState(__UpperCAmelCase		).standard_normal((1, 4, 6_4, 6_4)		)
         UpperCAmelCase__								=  torch.from_numpy(__UpperCAmelCase		).to(device=__UpperCAmelCase       ,  dtype=__UpperCAmelCase		)
         UpperCAmelCase__								=  {
             "prompt": "a photograph of an astronaut riding a horse",
             "latents": latents,
             "generator": generator,
             "num_inference_steps": 5_0,
             "guidance_scale": 7.5,
             "output_type": "numpy",
         }
         return inputs


   def 			lowercase_      (self     :						Any		)						->				Any:
         """simple docstring"""



         UpperCAmelCase__								=  StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d"		).to(__UpperCAmelCase		)
         ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

         UpperCAmelCase__								=  self.get_inputs(__UpperCAmelCase		)
         UpperCAmelCase__								=  ldmad_pipe(**__UpperCAmelCase		)
         UpperCAmelCase__		,      UpperCAmelCase__								=  output.rgb, output.depth

         UpperCAmelCase__								=  0.495586
         UpperCAmelCase__								=  0.33795515
         UpperCAmelCase__								=  112.48518
         UpperCAmelCase__								=  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 			lowercase_      (self     :						Tuple		)						->				Tuple:
         """simple docstring"""



         UpperCAmelCase__								=  StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d-4c"		).to(__UpperCAmelCase		)
         ldmad_pipe.set_progress_bar_config(disable=__UpperCAmelCase		)

         UpperCAmelCase__								=  self.get_inputs(__UpperCAmelCase		)
         UpperCAmelCase__								=  ldmad_pipe(**__UpperCAmelCase		)
         UpperCAmelCase__		,      UpperCAmelCase__								=  output.rgb, output.depth

         UpperCAmelCase__								=  0.4194127
         UpperCAmelCase__								=  0.35375586
         UpperCAmelCase__								=  0.5638502
         UpperCAmelCase__								=  0.34686103

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

from scipy.special import comb  # type: ignore





class      A							:


   def __init__(self     :						List[Any]       ,  __UpperCAmelCase     :						list[tuple[float, float]]		)						->				List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  list_of_points
         # Degree determines the flexibility of the curve.
         # Degree = 1 will produce a straight line.
         UpperCAmelCase__								=  len(__UpperCAmelCase		) - 1


   def 			lowercase_      (self     :						int       ,  __UpperCAmelCase     :						float		)						->				list[float]:
         """simple docstring"""



         assert 0 <= t <= 1, "Time t must be between 0 and 1."
         UpperCAmelCase__								=  []
         for i in range(len(self.list_of_points		)		):
               # basis function for each i
               output_values.append(
                   comb(self.degree       ,  __UpperCAmelCase		) * ((1 - t) ** (self.degree - i)) * (t**i)		)
         # the basis must sum up to 1 for it to produce a valid Bezier curve.
         assert round(sum(__UpperCAmelCase		)       ,  5		) == 1
         return output_values


   def 			lowercase_      (self     :						Dict       ,  __UpperCAmelCase     :						float		)						->				tuple[float, float]:
         """simple docstring"""



         assert 0 <= t <= 1, "Time t must be between 0 and 1."

         UpperCAmelCase__								=  self.basis_function(__UpperCAmelCase		)
         UpperCAmelCase__								=  0.0
         UpperCAmelCase__								=  0.0
         for i in range(len(self.list_of_points		)		):
               # For all points, sum up the product of i-th basis function and i-th point.
               x += basis_function[i] * self.list_of_points[i][0]
               y += basis_function[i] * self.list_of_points[i][1]
         return (x, y)





   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						float = 0.01		)						->				Optional[int]:
         """simple docstring"""



         from matplotlib import pyplot as plt  # type: ignore

         UpperCAmelCase__								=  []  # x coordinates of points to plot
         UpperCAmelCase__								=  []  # y coordinates of points to plot

         UpperCAmelCase__								=  0.0
         while t <= 1:
               UpperCAmelCase__								=  self.bezier_curve_function(__UpperCAmelCase		)
               to_plot_x.append(value[0]		)
               to_plot_y.append(value[1]		)
               t += step_size

         UpperCAmelCase__								=  [i[0] for i in self.list_of_points]
         UpperCAmelCase__								=  [i[1] for i in self.list_of_points]

         plt.plot(
             __UpperCAmelCase       ,  __UpperCAmelCase       ,  color="blue"       ,  label="Curve of Degree " + str(self.degree		)       ,  )
         plt.scatter(__UpperCAmelCase       ,  __UpperCAmelCase       ,  color="red"       ,  label="Control Points"		)
         plt.legend()
         plt.show()


if __name__ == "__main__":
      import doctest

      doctest.testmod()

      BezierCurve([(1, 2), (3, 5)]).plot_curve()  # degree 1
      BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve()  # degree 2
      BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve()  # degree 3



