
import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 					lowerCamelCase		(  A_							,			unittest.TestCase  ):
     UpperCAmelCase__    :							List[Any]									=		LDMTextToImagePipeline
     UpperCAmelCase__    :							Any									=		TEXT_TO_IMAGE_PARAMS - {
         "negative_prompt",
         "negative_prompt_embeds",
         "cross_attention_kwargs",
         "prompt_embeds",
     }
     UpperCAmelCase__    :							Tuple									=		PipelineTesterMixin.required_optional_params - {
         "num_images_per_prompt",
         "callback",
         "callback_steps",
     }
     UpperCAmelCase__    :							Any									=		TEXT_TO_IMAGE_BATCH_PARAMS
     UpperCAmelCase__    :							Union[str, Any]									=		False





     def 		UpperCAmelCase(self				:   Dict       )						->						Tuple:
         torch.manual_seed(0       )
         snake_case								= 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    ,   )
         snake_case								= DDIMScheduler(
             beta_start=0.0_00_85    ,   beta_end=0.0_12    ,   beta_schedule="scaled_linear"    ,   clip_sample=_A    ,   set_alpha_to_one=_A    ,   )
         torch.manual_seed(0       )
         snake_case								= 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    ,   )
         torch.manual_seed(0       )
         snake_case								= 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    ,   )
         snake_case								= CLIPTextModel(_A       )
         snake_case								= CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

         snake_case								= {
             "unet": unet,
             "scheduler": scheduler,
             "vqvae": vae,
             "bert": text_encoder,
             "tokenizer": tokenizer,
         }
         return components





     def 		UpperCAmelCase(self				:   Optional[Any]    ,   _A				:   List[str]    ,   _A				:   Dict=0       )						->						Optional[Any]:
         if str(_A       ).startswith("mps"       ):
             snake_case								= torch.manual_seed(_A       )
         else:
             snake_case								= torch.Generator(device=_A       ).manual_seed(_A       )
         snake_case								= {
             "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 		UpperCAmelCase(self				:   Optional[int]       )						->						str:
         snake_case								= "cpu"  # ensure determinism for the device-dependent torch.Generator

         snake_case								= self.get_dummy_components()
         snake_case								= LDMTextToImagePipeline(**_A       )
         pipe.to(_A       )
         pipe.set_progress_bar_config(disable=_A       )

         snake_case								= self.get_dummy_inputs(_A       )
         snake_case								= pipe(**_A       ).images
         snake_case								= image[0, -3:, -3:, -1]

         assert image.shape == (1, 1_6, 1_6, 3)
         snake_case								= np.array([0.61_01, 0.61_56, 0.56_22, 0.48_95, 0.66_61, 0.38_04, 0.57_48, 0.61_36, 0.50_14]       )

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







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





     def 		UpperCAmelCase(self				:   Dict       )						->						Any:
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()





     def 		UpperCAmelCase(self				:   int    ,   _A				:   Optional[Any]    ,   _A				:   Union[str, Any]=torch.floataa    ,   _A				:   str=0       )						->						Optional[Any]:
         snake_case								= torch.manual_seed(_A       )
         snake_case								= np.random.RandomState(_A       ).standard_normal((1, 4, 3_2, 3_2)       )
         snake_case								= torch.from_numpy(_A       ).to(device=_A    ,   dtype=_A       )
         snake_case								= {
             "prompt": "A painting of a squirrel eating a burger",
             "latents": latents,
             "generator": generator,
             "num_inference_steps": 3,
             "guidance_scale": 6.0,
             "output_type": "numpy",
         }
         return inputs





     def 		UpperCAmelCase(self				:   int       )						->						str:
         snake_case								= LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"       ).to(_A       )
         pipe.set_progress_bar_config(disable=_A       )

         snake_case								= self.get_inputs(_A       )
         snake_case								= pipe(**_A       ).images
         snake_case								= image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 2_5_6, 2_5_6, 3)
         snake_case								= np.array([0.5_18_25, 0.5_28_50, 0.5_25_43, 0.5_42_58, 0.5_23_04, 0.5_25_69, 0.5_43_63, 0.5_52_76, 0.5_68_78]       )
         snake_case								= np.abs(expected_slice - image_slice       ).max()
         assert max_diff < 1E-3







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





     def 		UpperCAmelCase(self				:   List[Any]       )						->						Optional[int]:
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()





     def 		UpperCAmelCase(self				:   int    ,   _A				:   Tuple    ,   _A				:   Any=torch.floataa    ,   _A				:   int=0       )						->						str:
         snake_case								= torch.manual_seed(_A       )
         snake_case								= np.random.RandomState(_A       ).standard_normal((1, 4, 3_2, 3_2)       )
         snake_case								= torch.from_numpy(_A       ).to(device=_A    ,   dtype=_A       )
         snake_case								= {
             "prompt": "A painting of a squirrel eating a burger",
             "latents": latents,
             "generator": generator,
             "num_inference_steps": 5_0,
             "guidance_scale": 6.0,
             "output_type": "numpy",
         }
         return inputs





     def 		UpperCAmelCase(self				:   Optional[int]       )						->						Optional[Any]:
         snake_case								= LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"       ).to(_A       )
         pipe.set_progress_bar_config(disable=_A       )

         snake_case								= self.get_inputs(_A       )
         snake_case								= pipe(**_A       ).images[0]

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



from __future__ import annotations

from decimal import Decimal

from numpy import array



def 						lowercase_      (       A__		)							->							list[list[float]]:
    """simple docstring"""

    snake_case								= Decimal

    # Check if the provided matrix has 2 rows and 2 columns
    # since this implementation only works for 2x2 matrices
    if len(A__		) == 2 and len(matrix[0]		) == 2 and len(matrix[1]		) == 2:
        # Calculate the determinant of the matrix
        snake_case								= float(
            d(matrix[0][0]		) * d(matrix[1][1]		) - d(matrix[1][0]		) * d(matrix[0][1]		)		)
        if determinant == 0:
            raise ValueError("This matrix has no inverse."		)

        # Creates a copy of the matrix with swapped positions of the elements
        snake_case								= [[0.0, 0.0], [0.0, 0.0]]
        snake_case					,							snake_case								= matrix[1][1], matrix[0][0]
        snake_case					,							snake_case								= -matrix[1][0], -matrix[0][1]

        # Calculate the inverse of the matrix
        return [
            [(float(d(A__		)		) / determinant) or 0.0 for n in row] for row in swapped_matrix
        ]
    elif (
        len(A__		) == 3
        and len(matrix[0]		) == 3
        and len(matrix[1]		) == 3
        and len(matrix[2]		) == 3
    ):
        # Calculate the determinant of the matrix using Sarrus rule
        snake_case								= float(
            (
                (d(matrix[0][0]		) * d(matrix[1][1]		) * d(matrix[2][2]		))
                + (d(matrix[0][1]		) * d(matrix[1][2]		) * d(matrix[2][0]		))
                + (d(matrix[0][2]		) * d(matrix[1][0]		) * d(matrix[2][1]		))
            )
            - (
                (d(matrix[0][2]		) * d(matrix[1][1]		) * d(matrix[2][0]		))
                + (d(matrix[0][1]		) * d(matrix[1][0]		) * d(matrix[2][2]		))
                + (d(matrix[0][0]		) * d(matrix[1][2]		) * d(matrix[2][1]		))
            )		)
        if determinant == 0:
            raise ValueError("This matrix has no inverse."		)

        # Creating cofactor matrix
        snake_case								= [
            [d(0.0		), d(0.0		), d(0.0		)],
            [d(0.0		), d(0.0		), d(0.0		)],
            [d(0.0		), d(0.0		), d(0.0		)],
        ]
        snake_case								= (d(matrix[1][1]		) * d(matrix[2][2]		)) - (
            d(matrix[1][2]		) * d(matrix[2][1]		)
        )
        snake_case								= -(
            (d(matrix[1][0]		) * d(matrix[2][2]		)) - (d(matrix[1][2]		) * d(matrix[2][0]		))
        )
        snake_case								= (d(matrix[1][0]		) * d(matrix[2][1]		)) - (
            d(matrix[1][1]		) * d(matrix[2][0]		)
        )
        snake_case								= -(
            (d(matrix[0][1]		) * d(matrix[2][2]		)) - (d(matrix[0][2]		) * d(matrix[2][1]		))
        )
        snake_case								= (d(matrix[0][0]		) * d(matrix[2][2]		)) - (
            d(matrix[0][2]		) * d(matrix[2][0]		)
        )
        snake_case								= -(
            (d(matrix[0][0]		) * d(matrix[2][1]		)) - (d(matrix[0][1]		) * d(matrix[2][0]		))
        )
        snake_case								= (d(matrix[0][1]		) * d(matrix[1][2]		)) - (
            d(matrix[0][2]		) * d(matrix[1][1]		)
        )
        snake_case								= -(
            (d(matrix[0][0]		) * d(matrix[1][2]		)) - (d(matrix[0][2]		) * d(matrix[1][0]		))
        )
        snake_case								= (d(matrix[0][0]		) * d(matrix[1][1]		)) - (
            d(matrix[0][1]		) * d(matrix[1][0]		)
        )

        # Transpose the cofactor matrix (Adjoint matrix)
        snake_case								= array(A__		)
        for i in range(3		):
            for j in range(3		):
                snake_case								= cofactor_matrix[j][i]

        # Inverse of the matrix using the formula (1/determinant) * adjoint matrix
        snake_case								= array(A__		)
        for i in range(3		):
            for j in range(3		):
                inverse_matrix[i][j] /= d(A__		)

        # Calculate the inverse of the matrix
        return [[float(d(A__		)		) or 0.0 for n in row] for row in inverse_matrix]
    raise ValueError("Please provide a matrix of size 2x2 or 3x3."		)

