'''simple docstring'''


import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import 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
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 					__SCREAMING_SNAKE_CASE						(	lowerCamelCase_						,     lowerCamelCase_						,     unittest.TestCase	):







  '''simple docstring'''






  lowerCamelCase_		:Any						   =		StableDiffusionSAGPipeline
  lowerCamelCase_		:Dict						   =		TEXT_TO_IMAGE_PARAMS
  lowerCamelCase_		:Dict						   =		TEXT_TO_IMAGE_BATCH_PARAMS
  lowerCamelCase_		:Union[str, Any]						   =		TEXT_TO_IMAGE_IMAGE_PARAMS
  lowerCamelCase_		:Optional[Any]						   =		TEXT_TO_IMAGE_IMAGE_PARAMS
  lowerCamelCase_		:Any						   =		False


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       torch.manual_seed(0						)
       UpperCAmelCase_							:       Optional[Any]       =				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_							:       List[Any]       =				DDIMScheduler(
           beta_start=0.0_00_85				,		beta_end=0.0_12				,		beta_schedule='scaled_linear'				,		clip_sample=snake_case_				,		set_alpha_to_one=snake_case_				,		)
       torch.manual_seed(0						)
       UpperCAmelCase_							:       Dict       =				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						)
       UpperCAmelCase_							:       Tuple       =				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_							:       Tuple       =				CLIPTextModel(snake_case_						)
       UpperCAmelCase_							:       Tuple       =				CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'						)

       UpperCAmelCase_							:       Tuple       =				{
           'unet': unet,
           'scheduler': scheduler,
           'vae': vae,
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'safety_checker': None,
           'feature_extractor': None,
       }
       return components


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_=0						):




       '''simple docstring'''

       if str(snake_case_						).startswith('mps'						):
            UpperCAmelCase_							:       Optional[Any]       =				torch.manual_seed(snake_case_						)
       else:
            UpperCAmelCase_							:       List[str]       =				torch.Generator(device=snake_case_						).manual_seed(snake_case_						)
       UpperCAmelCase_							:       List[Any]       =				{
           'prompt': '.',
           'generator': generator,
           'num_inference_steps': 2,
           'guidance_scale': 1.0,
           'sag_scale': 1.0,
           'output_type': 'numpy',
       }
       return inputs






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       super().test_inference_batch_single_identical(expected_max_diff=3E-3						)







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







  '''simple docstring'''






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       List[Any]       =				StableDiffusionSAGPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'						)
       UpperCAmelCase_							:       Any       =				sag_pipe.to(snake_case_						)
       sag_pipe.set_progress_bar_config(disable=snake_case_						)

       UpperCAmelCase_							:       Union[str, Any]       =				'.'
       UpperCAmelCase_							:       Tuple       =				torch.manual_seed(0						)
       UpperCAmelCase_							:       Dict       =				sag_pipe(
           [prompt]				,		generator=snake_case_				,		guidance_scale=7.5				,		sag_scale=1.0				,		num_inference_steps=2_0				,		output_type='np'						)

       UpperCAmelCase_							:       Any       =				output.images

       UpperCAmelCase_							:       Dict       =				image[0, -3:, -3:, -1]

       assert image.shape == (1, 5_1_2, 5_1_2, 3)
       UpperCAmelCase_							:       Tuple       =				np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]						)

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       Any       =				StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'						)
       UpperCAmelCase_							:       Optional[int]       =				sag_pipe.to(snake_case_						)
       sag_pipe.set_progress_bar_config(disable=snake_case_						)

       UpperCAmelCase_							:       List[Any]       =				'.'
       UpperCAmelCase_							:       List[str]       =				torch.manual_seed(0						)
       UpperCAmelCase_							:       str       =				sag_pipe(
           [prompt]				,		generator=snake_case_				,		guidance_scale=7.5				,		sag_scale=1.0				,		num_inference_steps=2_0				,		output_type='np'						)

       UpperCAmelCase_							:       List[str]       =				output.images

       UpperCAmelCase_							:       Tuple       =				image[0, -3:, -3:, -1]

       assert image.shape == (1, 5_1_2, 5_1_2, 3)
       UpperCAmelCase_							:       Tuple       =				np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]						)

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






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       str       =				StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'						)
       UpperCAmelCase_							:       str       =				sag_pipe.to(snake_case_						)
       sag_pipe.set_progress_bar_config(disable=snake_case_						)

       UpperCAmelCase_							:       Union[str, Any]       =				'.'
       UpperCAmelCase_							:       List[Any]       =				torch.manual_seed(0						)
       UpperCAmelCase_							:       List[str]       =				sag_pipe(
           [prompt]				,		width=7_6_8				,		height=5_1_2				,		generator=snake_case_				,		guidance_scale=7.5				,		sag_scale=1.0				,		num_inference_steps=2_0				,		output_type='np'				,		)

       UpperCAmelCase_							:       List[str]       =				output.images

       assert image.shape == (1, 5_1_2, 7_6_8, 3)







'''simple docstring'''


import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding






class 					__SCREAMING_SNAKE_CASE						(	lowerCamelCase_	):







  '''simple docstring'''






  lowerCamelCase_		:Tuple						   =		['''image_processor''', '''tokenizer''']
  lowerCamelCase_		:Optional[Any]						   =		'''ViTImageProcessor'''
  lowerCamelCase_		:int						   =		('''CLIPTokenizer''', '''CLIPTokenizerFast''')


  def __init__(			self				,		snake_case_=None				,		snake_case_=None				,		**snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_							:       Dict       =				None
       if "feature_extractor" in kwargs:
            warnings.warn(
                'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
                ' instead.'				,		snake_case_				,		)
            UpperCAmelCase_							:       int       =				kwargs.pop('feature_extractor'						)

       UpperCAmelCase_							:       str       =				image_processor if image_processor is not None else feature_extractor
       if image_processor is None:
            raise ValueError('You need to specify an `image_processor`.'						)
       if tokenizer is None:
            raise ValueError('You need to specify a `tokenizer`.'						)

       super().__init__(snake_case_				,		snake_case_						)


  def __call__(			self				,		snake_case_=None				,		snake_case_=None				,		snake_case_=None				,		snake_case_=None				,		**snake_case_						):




       '''simple docstring'''

       if text is None and visual_prompt is None and images is None:
            raise ValueError('You have to specify either text, visual prompt or images.'						)

       if text is not None and visual_prompt is not None:
            raise ValueError('You have to specify exactly one type of prompt. Either text or visual prompt.'						)

       if text is not None:
            UpperCAmelCase_							:       Optional[int]       =				self.tokenizer(snake_case_				,		return_tensors=snake_case_				,		**snake_case_						)

       if visual_prompt is not None:
            UpperCAmelCase_							:       Optional[Any]       =				self.image_processor(snake_case_				,		return_tensors=snake_case_				,		**snake_case_						)

       if images is not None:
            UpperCAmelCase_							:       int       =				self.image_processor(snake_case_				,		return_tensors=snake_case_				,		**snake_case_						)

       if visual_prompt is not None and images is not None:
            UpperCAmelCase_							:       Tuple       =				{
                'pixel_values': image_features.pixel_values,
                'conditional_pixel_values': prompt_features.pixel_values,
            }
            return encoding
       elif text is not None and images is not None:
            UpperCAmelCase_							:       Optional[int]       =				image_features.pixel_values
            return encoding
       elif text is not None:
            return encoding
       elif visual_prompt is not None:
            UpperCAmelCase_							:       Dict       =				{
                'conditional_pixel_values': prompt_features.pixel_values,
            }
            return encoding
       else:
            return BatchEncoding(data=dict(**snake_case_						)				,		tensor_type=snake_case_						)


  def _UpperCamelCase					(			self				,		*snake_case_				,		**snake_case_						):




       '''simple docstring'''

       return self.tokenizer.batch_decode(*snake_case_				,		**snake_case_						)


  def _UpperCamelCase					(			self				,		*snake_case_				,		**snake_case_						):




       '''simple docstring'''

       return self.tokenizer.decode(*snake_case_				,		**snake_case_						)


  @property
  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       warnings.warn(
           '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'				,		snake_case_				,		)
       return self.image_processor_class






  @property
  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       warnings.warn(
           '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'				,		snake_case_				,		)
       return self.image_processor






