





import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class 			lowerCAmelCase__( unittest.TestCase    ):






       '''simple docstring'''


       def     UpperCamelCase_			(      self							)			->     List[str]:
            # clean up the VRAM after each test
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()




       @property
       def     UpperCamelCase_			(      self							)			->     Any:
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							1
            _SCREAMING_SNAKE_CASE       :	Any						    =							3
            _SCREAMING_SNAKE_CASE       :	Dict						    =							(3_2, 3_2)

            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							floats_tensor((batch_size, num_channels) + sizes    ,						rng=random.Random(0							)							).to(__lowerCamelCase							)
            return image




       @property
       def     UpperCamelCase_			(      self							)			->     str:
            torch.manual_seed(0							)
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							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    ,						)
            return model




       @property
       def     UpperCamelCase_			(      self							)			->     Union[str, Any]:
            torch.manual_seed(0							)
            _SCREAMING_SNAKE_CASE       :	Any						    =							AutoencoderKL(
                block_out_channels=[3_2, 6_4]    ,						in_channels=3    ,						out_channels=3    ,						down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]    ,						up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]    ,						latent_channels=4    ,						)
            return model




       @property
       def     UpperCamelCase_			(      self							)			->     Optional[int]:
            torch.manual_seed(0							)
            _SCREAMING_SNAKE_CASE       :	Dict						    =							RobertaSeriesConfig(
                hidden_size=3_2    ,						project_dim=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=5_0_0_6    ,						)
            return RobertaSeriesModelWithTransformation(__lowerCamelCase							)




       @property
       def     UpperCamelCase_			(      self							)			->     str:
            def extract(*__lowerCamelCase    ,						**__lowerCamelCase							):





                 class 			lowerCAmelCase__:






                        '''simple docstring'''


                        def __init__(      self							)			->     Dict:
                             _SCREAMING_SNAKE_CASE       :	List[str]						    =							torch.ones([0]							)







                        def     UpperCamelCase_			(      self    ,						__lowerCamelCase							)			->     Optional[int]:
                             self.pixel_values.to(__lowerCamelCase							)
                             return self
                 return Out()

            return extract




       def     UpperCamelCase_			(      self							)			->     Any:
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							"cpu"  # ensure determinism for the device-dependent torch.Generator
            _SCREAMING_SNAKE_CASE       :	Dict						    =							self.dummy_cond_unet
            _SCREAMING_SNAKE_CASE       :	int						    =							PNDMScheduler(skip_prk_steps=__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							self.dummy_vae
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							self.dummy_text_encoder
            _SCREAMING_SNAKE_CASE       :	int						    =							XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"							)
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							7_7

            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							self.dummy_image.to(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							init_image / 2 + 0.5

            # make sure here that pndm scheduler skips prk
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							AltDiffusionImgaImgPipeline(
                unet=__lowerCamelCase    ,						scheduler=__lowerCamelCase    ,						vae=__lowerCamelCase    ,						text_encoder=__lowerCamelCase    ,						tokenizer=__lowerCamelCase    ,						safety_checker=__lowerCamelCase    ,						feature_extractor=self.dummy_extractor    ,						)
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor    ,						do_normalize=__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							alt_pipe.to(__lowerCamelCase							)
            alt_pipe.set_progress_bar_config(disable=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE       :	Dict						    =							"A painting of a squirrel eating a burger"
            _SCREAMING_SNAKE_CASE       :	str						    =							torch.Generator(device=__lowerCamelCase							).manual_seed(0							)
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							alt_pipe(
                [prompt]    ,						generator=__lowerCamelCase    ,						guidance_scale=6.0    ,						num_inference_steps=2    ,						output_type="np"    ,						image=__lowerCamelCase    ,						)

            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							output.images

            _SCREAMING_SNAKE_CASE       :	Any						    =							torch.Generator(device=__lowerCamelCase							).manual_seed(0							)
            _SCREAMING_SNAKE_CASE       :	Any						    =							alt_pipe(
                [prompt]    ,						generator=__lowerCamelCase    ,						guidance_scale=6.0    ,						num_inference_steps=2    ,						output_type="np"    ,						image=__lowerCamelCase    ,						return_dict=__lowerCamelCase    ,						)[0]

            _SCREAMING_SNAKE_CASE       :	Any						    =							image[0, -3:, -3:, -1]
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							image_from_tuple[0, -3:, -3:, -1]

            assert image.shape == (1, 3_2, 3_2, 3)
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]							)

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




       @unittest.skipIf(torch_device != "cuda"    ,						"This test requires a GPU"							)
       def     UpperCamelCase_			(      self							)			->     Dict:
            _SCREAMING_SNAKE_CASE       :	str						    =							self.dummy_cond_unet
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							PNDMScheduler(skip_prk_steps=__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							self.dummy_vae
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							self.dummy_text_encoder
            _SCREAMING_SNAKE_CASE       :	Dict						    =							XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"							)
            _SCREAMING_SNAKE_CASE       :	str						    =							7_7

            _SCREAMING_SNAKE_CASE       :	List[str]						    =							self.dummy_image.to(__lowerCamelCase							)

            # put models in fp16
            _SCREAMING_SNAKE_CASE       :	str						    =							unet.half()
            _SCREAMING_SNAKE_CASE       :	Any						    =							vae.half()
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							bert.half()

            # make sure here that pndm scheduler skips prk
            _SCREAMING_SNAKE_CASE       :	int						    =							AltDiffusionImgaImgPipeline(
                unet=__lowerCamelCase    ,						scheduler=__lowerCamelCase    ,						vae=__lowerCamelCase    ,						text_encoder=__lowerCamelCase    ,						tokenizer=__lowerCamelCase    ,						safety_checker=__lowerCamelCase    ,						feature_extractor=self.dummy_extractor    ,						)
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor    ,						do_normalize=__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	str						    =							alt_pipe.to(__lowerCamelCase							)
            alt_pipe.set_progress_bar_config(disable=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE       :	Any						    =							"A painting of a squirrel eating a burger"
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							torch.manual_seed(0							)
            _SCREAMING_SNAKE_CASE       :	int						    =							alt_pipe(
                [prompt]    ,						generator=__lowerCamelCase    ,						num_inference_steps=2    ,						output_type="np"    ,						image=__lowerCamelCase    ,						).images

            assert image.shape == (1, 3_2, 3_2, 3)







       @unittest.skipIf(torch_device != "cuda"    ,						"This test requires a GPU"							)
       def     UpperCamelCase_			(      self							)			->     List[Any]:
            _SCREAMING_SNAKE_CASE       :	str						    =							load_image(
                "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                "/img2img/sketch-mountains-input.jpg"							)
            # resize to resolution that is divisible by 8 but not 16 or 32
            _SCREAMING_SNAKE_CASE       :	str						    =							init_image.resize((7_6_0, 5_0_4)							)

            _SCREAMING_SNAKE_CASE       :	str						    =							"BAAI/AltDiffusion"
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							AltDiffusionImgaImgPipeline.from_pretrained(
                __lowerCamelCase    ,						safety_checker=__lowerCamelCase    ,						)
            pipe.to(__lowerCamelCase							)
            pipe.set_progress_bar_config(disable=__lowerCamelCase							)
            pipe.enable_attention_slicing()

            _SCREAMING_SNAKE_CASE       :	Tuple						    =							"A fantasy landscape, trending on artstation"

            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							torch.manual_seed(0							)
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							pipe(
                prompt=__lowerCamelCase    ,						image=__lowerCamelCase    ,						strength=0.75    ,						guidance_scale=7.5    ,						generator=__lowerCamelCase    ,						output_type="np"    ,						)
            _SCREAMING_SNAKE_CASE       :	str						    =							output.images[0]

            _SCREAMING_SNAKE_CASE       :	str						    =							image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

            assert image.shape == (5_0_4, 7_6_0, 3)
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]							)

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





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






       '''simple docstring'''


       def     UpperCamelCase_			(      self							)			->     int:
            # clean up the VRAM after each test
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()







       def     UpperCamelCase_			(      self							)			->     Union[str, Any]:
            _SCREAMING_SNAKE_CASE       :	int						    =							load_image(
                "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                "/img2img/sketch-mountains-input.jpg"							)
            _SCREAMING_SNAKE_CASE       :	Any						    =							init_image.resize((7_6_8, 5_1_2)							)
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							load_numpy(
                "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"							)

            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							"BAAI/AltDiffusion"
            _SCREAMING_SNAKE_CASE       :	Any						    =							AltDiffusionImgaImgPipeline.from_pretrained(
                __lowerCamelCase    ,						safety_checker=__lowerCamelCase    ,						)
            pipe.to(__lowerCamelCase							)
            pipe.set_progress_bar_config(disable=__lowerCamelCase							)
            pipe.enable_attention_slicing()

            _SCREAMING_SNAKE_CASE       :	int						    =							"A fantasy landscape, trending on artstation"

            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							torch.manual_seed(0							)
            _SCREAMING_SNAKE_CASE       :	str						    =							pipe(
                prompt=__lowerCamelCase    ,						image=__lowerCamelCase    ,						strength=0.75    ,						guidance_scale=7.5    ,						generator=__lowerCamelCase    ,						output_type="np"    ,						)
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							output.images[0]

            assert image.shape == (5_1_2, 7_6_8, 3)
            # img2img is flaky across GPUs even in fp32, so using MAE here
            assert np.abs(expected_image - image							).max() < 1E-2






from __future__ import annotations

from scipy.special import comb  # type: ignore





class 			lowerCAmelCase__:






       '''simple docstring'''


       def __init__(      self    ,						__lowerCamelCase							)			->     Tuple:
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							list_of_points
            # Degree determines the flexibility of the curve.
            # Degree = 1 will produce a straight line.
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							len(__lowerCamelCase							) - 1




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase							)			->     list[float]:
            assert 0 <= t <= 1, "Time t must be between 0 and 1."
            _SCREAMING_SNAKE_CASE       :	list[float]						    =							[]
            for i in range(len(self.list_of_points							)							):
                 # basis function for each i
                 output_values.append(
                     comb(self.degree    ,						__lowerCamelCase							) * ((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(__lowerCamelCase							)    ,						5							) == 1
            return output_values




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase							)			->     tuple[float, float]:
            assert 0 <= t <= 1, "Time t must be between 0 and 1."

            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							self.basis_function(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	str						    =							0.0
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							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     UpperCamelCase_			(      self    ,						__lowerCamelCase = 0.01							)			->     int:
            from matplotlib import pyplot as plt  # type: ignore

            _SCREAMING_SNAKE_CASE       :	list[float]						    =							[]  # x coordinates of points to plot
            _SCREAMING_SNAKE_CASE       :	list[float]						    =							[]  # y coordinates of points to plot

            _SCREAMING_SNAKE_CASE       :	Dict						    =							0.0
            while t <= 1:
                 _SCREAMING_SNAKE_CASE       :	str						    =							self.bezier_curve_function(__lowerCamelCase							)
                 to_plot_x.append(value[0]							)
                 to_plot_y.append(value[1]							)
                 t += step_size

            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							[i[0] for i in self.list_of_points]
            _SCREAMING_SNAKE_CASE       :	Dict						    =							[i[1] for i in self.list_of_points]

            plt.plot(
                __lowerCamelCase    ,						__lowerCamelCase    ,						color="blue"    ,						label="Curve of Degree " + str(self.degree							)    ,						)
            plt.scatter(__lowerCamelCase    ,						__lowerCamelCase    ,						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