

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							):




  def 						A__  (       self      )						->				Optional[int]:
        '''simple docstring'''






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




  @property
  def 						A__  (       self      )						->				Optional[int]:
        '''simple docstring'''






        _lowercase			 =1
        _lowercase			 =3
        _lowercase			 =(32, 32)

        _lowercase			 =floats_tensor((batch_size, num_channels) + sizes							,     rng=random.Random(0      )      ).to(lowerCAmelCase      )
        return image




  @property
  def 						A__  (       self      )						->				Tuple:
        '''simple docstring'''






        torch.manual_seed(0      )
        _lowercase			 =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							,     )
        return model




  @property
  def 						A__  (       self      )						->				Union[str, Any]:
        '''simple docstring'''






        torch.manual_seed(0      )
        _lowercase			 =AutoencoderKL(
            block_out_channels=[32, 64]							,     in_channels=3							,     out_channels=3							,     down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']							,     up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']							,     latent_channels=4							,     )
        return model




  @property
  def 						A__  (       self      )						->				List[str]:
        '''simple docstring'''






        torch.manual_seed(0      )
        _lowercase			 =RobertaSeriesConfig(
            hidden_size=32							,     project_dim=32							,     intermediate_size=37							,     layer_norm_eps=1e-05							,     num_attention_heads=4							,     num_hidden_layers=5							,     pad_token_id=1							,     vocab_size=5_006							,     )
        return RobertaSeriesModelWithTransformation(lowerCAmelCase      )




  @property
  def 						A__  (       self      )						->				Optional[Any]:
        '''simple docstring'''






        def extract(*lowerCAmelCase							,     **lowerCAmelCase      ):





              class 				__lowerCAmelCase  :




                def __init__(       self      )						->				str:
                      '''simple docstring'''






                      _lowercase			 =torch.ones([0]      )




                def 						A__  (       self							,     lowerCAmelCase      )						->				List[Any]:
                      '''simple docstring'''






                      self.pixel_values.to(lowerCAmelCase      )
                      return self
              return Out()

        return extract




  def 						A__  (       self      )						->				Dict:
        '''simple docstring'''






        _lowercase			 ='cpu'  # ensure determinism for the device-dependent torch.Generator
        _lowercase			 =self.dummy_cond_unet
        _lowercase			 =PNDMScheduler(skip_prk_steps=lowerCAmelCase      )
        _lowercase			 =self.dummy_vae
        _lowercase			 =self.dummy_text_encoder
        _lowercase			 =XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'      )
        _lowercase			 =77

        _lowercase			 =self.dummy_image.to(lowerCAmelCase      )
        _lowercase			 =init_image / 2 + 0.5

        # make sure here that pndm scheduler skips prk
        _lowercase			 =AltDiffusionImgaImgPipeline(
            unet=lowerCAmelCase							,     scheduler=lowerCAmelCase							,     vae=lowerCAmelCase							,     text_encoder=lowerCAmelCase							,     tokenizer=lowerCAmelCase							,     safety_checker=lowerCAmelCase							,     feature_extractor=self.dummy_extractor							,     )
        _lowercase			 =VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,     do_normalize=lowerCAmelCase      )
        _lowercase			 =alt_pipe.to(lowerCAmelCase      )
        alt_pipe.set_progress_bar_config(disable=lowerCAmelCase      )

        _lowercase			 ='A painting of a squirrel eating a burger'
        _lowercase			 =torch.Generator(device=lowerCAmelCase      ).manual_seed(0      )
        _lowercase			 =alt_pipe(
            [prompt]							,     generator=lowerCAmelCase							,     guidance_scale=6.0							,     num_inference_steps=2							,     output_type='np'							,     image=lowerCAmelCase							,     )

        _lowercase			 =output.images

        _lowercase			 =torch.Generator(device=lowerCAmelCase      ).manual_seed(0      )
        _lowercase			 =alt_pipe(
            [prompt]							,     generator=lowerCAmelCase							,     guidance_scale=6.0							,     num_inference_steps=2							,     output_type='np'							,     image=lowerCAmelCase							,     return_dict=lowerCAmelCase							,     )[0]

        _lowercase			 =image[0, -3:, -3:, -1]
        _lowercase			 =image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 32, 32, 3)
        _lowercase			 =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 						A__  (       self      )						->				List[Any]:
        '''simple docstring'''






        _lowercase			 =self.dummy_cond_unet
        _lowercase			 =PNDMScheduler(skip_prk_steps=lowerCAmelCase      )
        _lowercase			 =self.dummy_vae
        _lowercase			 =self.dummy_text_encoder
        _lowercase			 =XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'      )
        _lowercase			 =77

        _lowercase			 =self.dummy_image.to(lowerCAmelCase      )

        # put models in fp16
        _lowercase			 =unet.half()
        _lowercase			 =vae.half()
        _lowercase			 =bert.half()

        # make sure here that pndm scheduler skips prk
        _lowercase			 =AltDiffusionImgaImgPipeline(
            unet=lowerCAmelCase							,     scheduler=lowerCAmelCase							,     vae=lowerCAmelCase							,     text_encoder=lowerCAmelCase							,     tokenizer=lowerCAmelCase							,     safety_checker=lowerCAmelCase							,     feature_extractor=self.dummy_extractor							,     )
        _lowercase			 =VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,     do_normalize=lowerCAmelCase      )
        _lowercase			 =alt_pipe.to(lowerCAmelCase      )
        alt_pipe.set_progress_bar_config(disable=lowerCAmelCase      )

        _lowercase			 ='A painting of a squirrel eating a burger'
        _lowercase			 =torch.manual_seed(0      )
        _lowercase			 =alt_pipe(
            [prompt]							,     generator=lowerCAmelCase							,     num_inference_steps=2							,     output_type='np'							,     image=lowerCAmelCase							,     ).images

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




  @unittest.skipIf(torch_device != 'cuda'							,     'This test requires a GPU'      )
  def 						A__  (       self      )						->				Optional[Any]:
        '''simple docstring'''






        _lowercase			 =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
        _lowercase			 =init_image.resize((760, 504)      )

        _lowercase			 ='BAAI/AltDiffusion'
        _lowercase			 =AltDiffusionImgaImgPipeline.from_pretrained(
            lowerCAmelCase							,     safety_checker=lowerCAmelCase							,     )
        pipe.to(lowerCAmelCase      )
        pipe.set_progress_bar_config(disable=lowerCAmelCase      )
        pipe.enable_attention_slicing()

        _lowercase			 ='A fantasy landscape, trending on artstation'

        _lowercase			 =torch.manual_seed(0      )
        _lowercase			 =pipe(
            prompt=lowerCAmelCase							,     image=lowerCAmelCase							,     strength=0.75							,     guidance_scale=7.5							,     generator=lowerCAmelCase							,     output_type='np'							,     )
        _lowercase			 =output.images[0]

        _lowercase			 =image[255:258, 383:386, -1]

        assert image.shape == (504, 760, 3)
        _lowercase			 =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							):




  def 						A__  (       self      )						->				Tuple:
        '''simple docstring'''






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




  def 						A__  (       self      )						->				int:
        '''simple docstring'''






        _lowercase			 =load_image(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
            '/img2img/sketch-mountains-input.jpg'      )
        _lowercase			 =init_image.resize((768, 512)      )
        _lowercase			 =load_numpy(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'      )

        _lowercase			 ='BAAI/AltDiffusion'
        _lowercase			 =AltDiffusionImgaImgPipeline.from_pretrained(
            lowerCAmelCase							,     safety_checker=lowerCAmelCase							,     )
        pipe.to(lowerCAmelCase      )
        pipe.set_progress_bar_config(disable=lowerCAmelCase      )
        pipe.enable_attention_slicing()

        _lowercase			 ='A fantasy landscape, trending on artstation'

        _lowercase			 =torch.manual_seed(0      )
        _lowercase			 =pipe(
            prompt=lowerCAmelCase							,     image=lowerCAmelCase							,     strength=0.75							,     guidance_scale=7.5							,     generator=lowerCAmelCase							,     output_type='np'							,     )
        _lowercase			 =output.images[0]

        assert image.shape == (512, 768, 3)
        # img2img is flaky across GPUs even in fp32, so using MAE here
        assert np.abs(expected_image - image      ).max() < 1e-2





def   a   (    A__			:     str   ,     A__			:     int  )					->   list[str]:





      """simple docstring"""



      return [sentence[i : i + ngram_size] for i in range(len(A__  ) - ngram_size + 1  )]


if __name__ == "__main__":
  from doctest import testmod

  testmod()


