


"""simple docstring"""







import gc
import random
import tempfile
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu


class       SCREAMING_SNAKE_CASE__				(		unittest.TestCase				):
       """simple docstring"""


       def        lowercase__							(						self						):






         """simple docstring"""





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

       @property
       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     int								=							1
         lowerCAmelCase     :     Optional[int]								=							3
         lowerCAmelCase     :     List[Any]								=							(32, 32)

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

       @property
       def        lowercase__							(						self						):






         """simple docstring"""





         torch.manual_seed(0						)
         lowerCAmelCase     :     Tuple								=							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        lowercase__							(						self						):






         """simple docstring"""





         torch.manual_seed(0						)
         lowerCAmelCase     :     int								=							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        lowercase__							(						self						):






         """simple docstring"""





         torch.manual_seed(0						)
         lowerCAmelCase     :     str								=							CLIPTextConfig(
             bos_token_id=0		,     eos_token_id=2		,     hidden_size=32		,     intermediate_size=37		,     layer_norm_eps=1e-05		,     num_attention_heads=4		,     num_hidden_layers=5		,     pad_token_id=1		,     vocab_size=1_000		,     )
         return CLIPTextModel(snake_case__						)

       @property
       def        lowercase__							(						self						):






         """simple docstring"""





         def extract(*snake_case__		,     **snake_case__						):


           class       SCREAMING_SNAKE_CASE__				:
                  """simple docstring"""


                  def __init__(						self						):






                    """simple docstring"""





                    lowerCAmelCase     :     int								=							torch.ones([0]						)







                  def        lowercase__							(						self		,     snake_case__						):






                    """simple docstring"""





                    self.pixel_values.to(snake_case__						)
                    return self

           return Out()

         return extract

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     Any								=							"cpu"  # ensure determinism for the device-dependent torch.Generator
         lowerCAmelCase     :     Dict								=							self.dummy_cond_unet
         lowerCAmelCase     :     List[str]								=							DDIMScheduler(
             beta_start=0.00085		,     beta_end=0.012		,     beta_schedule="scaled_linear"		,     clip_sample=snake_case__		,     set_alpha_to_one=snake_case__		,     )

         lowerCAmelCase     :     Union[str, Any]								=							self.dummy_vae
         lowerCAmelCase     :     List[Any]								=							self.dummy_text_encoder
         lowerCAmelCase     :     Optional[Any]								=							CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						)

         # make sure here that pndm scheduler skips prk
         lowerCAmelCase     :     Any								=							StableDiffusionPipeline(
             unet=snake_case__		,     scheduler=snake_case__		,     vae=snake_case__		,     text_encoder=snake_case__		,     tokenizer=snake_case__		,     safety_checker=snake_case__		,     feature_extractor=self.dummy_extractor		,     )
         lowerCAmelCase     :     List[str]								=							sd_pipe.to(snake_case__						)
         sd_pipe.set_progress_bar_config(disable=snake_case__						)

         lowerCAmelCase     :     Union[str, Any]								=							"A painting of a squirrel eating a burger"

         lowerCAmelCase     :     str								=							torch.Generator(device=snake_case__						).manual_seed(0						)
         lowerCAmelCase     :     int								=							sd_pipe([prompt]		,     generator=snake_case__		,     guidance_scale=6.0		,     num_inference_steps=2		,     output_type="np"						)
         lowerCAmelCase     :     str								=							output.images

         lowerCAmelCase     :     List[str]								=							torch.Generator(device=snake_case__						).manual_seed(0						)
         lowerCAmelCase     :     Optional[int]								=							sd_pipe(
             [prompt]		,     generator=snake_case__		,     guidance_scale=6.0		,     num_inference_steps=2		,     output_type="np"		,     return_dict=snake_case__		,     )[0]

         lowerCAmelCase     :     Any								=							image[0, -3:, -3:, -1]
         lowerCAmelCase     :     List[str]								=							image_from_tuple[0, -3:, -3:, -1]

         assert image.shape == (1, 64, 64, 3)
         lowerCAmelCase     :     Any								=							np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864]						)

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

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     Optional[int]								=							"cpu"  # ensure determinism for the device-dependent torch.Generator
         lowerCAmelCase     :     Optional[Any]								=							self.dummy_cond_unet
         lowerCAmelCase     :     Any								=							PNDMScheduler(skip_prk_steps=snake_case__						)
         lowerCAmelCase     :     Union[str, Any]								=							self.dummy_vae
         lowerCAmelCase     :     str								=							self.dummy_text_encoder
         lowerCAmelCase     :     Any								=							CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						)

         # make sure here that pndm scheduler skips prk
         lowerCAmelCase     :     Union[str, Any]								=							StableDiffusionPipeline(
             unet=snake_case__		,     scheduler=snake_case__		,     vae=snake_case__		,     text_encoder=snake_case__		,     tokenizer=snake_case__		,     safety_checker=snake_case__		,     feature_extractor=self.dummy_extractor		,     )
         lowerCAmelCase     :     Optional[int]								=							sd_pipe.to(snake_case__						)
         sd_pipe.set_progress_bar_config(disable=snake_case__						)

         lowerCAmelCase     :     Union[str, Any]								=							"A painting of a squirrel eating a burger"
         lowerCAmelCase     :     List[str]								=							torch.Generator(device=snake_case__						).manual_seed(0						)
         lowerCAmelCase     :     str								=							sd_pipe([prompt]		,     generator=snake_case__		,     guidance_scale=6.0		,     num_inference_steps=2		,     output_type="np"						)

         lowerCAmelCase     :     Union[str, Any]								=							output.images

         lowerCAmelCase     :     str								=							torch.Generator(device=snake_case__						).manual_seed(0						)
         lowerCAmelCase     :     Tuple								=							sd_pipe(
             [prompt]		,     generator=snake_case__		,     guidance_scale=6.0		,     num_inference_steps=2		,     output_type="np"		,     return_dict=snake_case__		,     )[0]

         lowerCAmelCase     :     List[str]								=							image[0, -3:, -3:, -1]
         lowerCAmelCase     :     Optional[Any]								=							image_from_tuple[0, -3:, -3:, -1]

         assert image.shape == (1, 64, 64, 3)
         lowerCAmelCase     :     List[Any]								=							np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993]						)

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

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     str								=							StableDiffusionPipeline.from_pretrained(
             "hf-internal-testing/tiny-stable-diffusion-lms-pipe"		,     safety_checker=snake_case__						)
         assert isinstance(snake_case__		,     snake_case__						)
         assert isinstance(pipe.scheduler		,     snake_case__						)
         assert pipe.safety_checker is None

         lowerCAmelCase     :     Dict								=							pipe("example prompt"		,     num_inference_steps=2						).images[0]
         assert image is not None

         # check that there's no error when saving a pipeline with one of the models being None
         with tempfile.TemporaryDirectory() as tmpdirname:
           pipe.save_pretrained(snake_case__						)
           lowerCAmelCase     :     Dict								=							StableDiffusionPipeline.from_pretrained(snake_case__						)

         # sanity check that the pipeline still works
         assert pipe.safety_checker is None
         lowerCAmelCase     :     str								=							pipe("example prompt"		,     num_inference_steps=2						).images[0]
         assert image is not None







       @unittest.skipIf(torch_device != "cuda"		,     "This test requires a GPU"						)
       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     int								=							self.dummy_cond_unet
         lowerCAmelCase     :     Dict								=							PNDMScheduler(skip_prk_steps=snake_case__						)
         lowerCAmelCase     :     str								=							self.dummy_vae
         lowerCAmelCase     :     List[Any]								=							self.dummy_text_encoder
         lowerCAmelCase     :     Union[str, Any]								=							CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						)

         # put models in fp16
         lowerCAmelCase     :     str								=							unet.half()
         lowerCAmelCase     :     Union[str, Any]								=							vae.half()
         lowerCAmelCase     :     Any								=							bert.half()

         # make sure here that pndm scheduler skips prk
         lowerCAmelCase     :     str								=							StableDiffusionPipeline(
             unet=snake_case__		,     scheduler=snake_case__		,     vae=snake_case__		,     text_encoder=snake_case__		,     tokenizer=snake_case__		,     safety_checker=snake_case__		,     feature_extractor=self.dummy_extractor		,     )
         lowerCAmelCase     :     Optional[Any]								=							sd_pipe.to(snake_case__						)
         sd_pipe.set_progress_bar_config(disable=snake_case__						)

         lowerCAmelCase     :     List[Any]								=							"A painting of a squirrel eating a burger"
         lowerCAmelCase     :     Any								=							sd_pipe([prompt]		,     num_inference_steps=2		,     output_type="np"						).images

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


@nightly
@require_torch_gpu
class       SCREAMING_SNAKE_CASE__				(		unittest.TestCase				):
       """simple docstring"""


       def        lowercase__							(						self						):






         """simple docstring"""





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

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     Dict								=							StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"		,     safety_checker=snake_case__						)
         lowerCAmelCase     :     Optional[Any]								=							LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config						)
         lowerCAmelCase     :     Tuple								=							sd_pipe.to(snake_case__						)
         sd_pipe.set_progress_bar_config(disable=snake_case__						)

         lowerCAmelCase     :     Dict								=							(
             "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle"
             " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with"
             " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and"
             " children from bahnhof zoo, detailed "
         )
         lowerCAmelCase     :     Any								=							4_003_660_346
         lowerCAmelCase     :     List[str]								=							7

         # without safety guidance (sld_guidance_scale = 0)
         lowerCAmelCase     :     Dict								=							torch.manual_seed(snake_case__						)
         lowerCAmelCase     :     str								=							sd_pipe(
             [prompt]		,     generator=snake_case__		,     guidance_scale=snake_case__		,     num_inference_steps=50		,     output_type="np"		,     width=512		,     height=512		,     sld_guidance_scale=0		,     )

         lowerCAmelCase     :     Optional[int]								=							output.images
         lowerCAmelCase     :     List[str]								=							image[0, -3:, -3:, -1]
         lowerCAmelCase     :     str								=							[0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176]

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

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

         # without safety guidance (strong configuration)
         lowerCAmelCase     :     int								=							torch.manual_seed(snake_case__						)
         lowerCAmelCase     :     Optional[int]								=							sd_pipe(
             [prompt]		,     generator=snake_case__		,     guidance_scale=snake_case__		,     num_inference_steps=50		,     output_type="np"		,     width=512		,     height=512		,     sld_guidance_scale=2_000		,     sld_warmup_steps=7		,     sld_threshold=0.025		,     sld_momentum_scale=0.5		,     sld_mom_beta=0.7		,     )

         lowerCAmelCase     :     Optional[Any]								=							output.images
         lowerCAmelCase     :     Tuple								=							image[0, -3:, -3:, -1]
         lowerCAmelCase     :     Tuple								=							[0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719]

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

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

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     int								=							StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"		,     safety_checker=snake_case__						)
         lowerCAmelCase     :     Optional[Any]								=							LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config						)
         lowerCAmelCase     :     Optional[Any]								=							sd_pipe.to(snake_case__						)
         sd_pipe.set_progress_bar_config(disable=snake_case__						)

         lowerCAmelCase     :     str								=							"padme amidala taking a bath artwork, safe for work, no nudity"
         lowerCAmelCase     :     Tuple								=							2_734_971_755
         lowerCAmelCase     :     Dict								=							7

         lowerCAmelCase     :     str								=							torch.manual_seed(snake_case__						)
         lowerCAmelCase     :     List[str]								=							sd_pipe(
             [prompt]		,     generator=snake_case__		,     guidance_scale=snake_case__		,     num_inference_steps=50		,     output_type="np"		,     width=512		,     height=512		,     sld_guidance_scale=0		,     )

         lowerCAmelCase     :     List[Any]								=							output.images
         lowerCAmelCase     :     List[str]								=							image[0, -3:, -3:, -1]
         lowerCAmelCase     :     Any								=							[0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297]

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

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

         lowerCAmelCase     :     List[str]								=							torch.manual_seed(snake_case__						)
         lowerCAmelCase     :     Union[str, Any]								=							sd_pipe(
             [prompt]		,     generator=snake_case__		,     guidance_scale=snake_case__		,     num_inference_steps=50		,     output_type="np"		,     width=512		,     height=512		,     sld_guidance_scale=2_000		,     sld_warmup_steps=7		,     sld_threshold=0.025		,     sld_momentum_scale=0.5		,     sld_mom_beta=0.7		,     )

         lowerCAmelCase     :     List[Any]								=							output.images
         lowerCAmelCase     :     List[str]								=							image[0, -3:, -3:, -1]
         lowerCAmelCase     :     Optional[Any]								=							[0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443]

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

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







       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     List[Any]								=							StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"						)
         lowerCAmelCase     :     Union[str, Any]								=							sd_pipe.to(snake_case__						)
         sd_pipe.set_progress_bar_config(disable=snake_case__						)

         lowerCAmelCase     :     Optional[int]								=							(
             "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c."
             " leyendecker"
         )
         lowerCAmelCase     :     Dict								=							1_044_355_234
         lowerCAmelCase     :     Any								=							12

         lowerCAmelCase     :     Tuple								=							torch.manual_seed(snake_case__						)
         lowerCAmelCase     :     Optional[Any]								=							sd_pipe(
             [prompt]		,     generator=snake_case__		,     guidance_scale=snake_case__		,     num_inference_steps=50		,     output_type="np"		,     width=512		,     height=512		,     sld_guidance_scale=0		,     )

         lowerCAmelCase     :     int								=							output.images
         lowerCAmelCase     :     Optional[Any]								=							image[0, -3:, -3:, -1]
         lowerCAmelCase     :     int								=							np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]						)

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

         assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-7

         lowerCAmelCase     :     Optional[int]								=							torch.manual_seed(snake_case__						)
         lowerCAmelCase     :     Optional[Any]								=							sd_pipe(
             [prompt]		,     generator=snake_case__		,     guidance_scale=snake_case__		,     num_inference_steps=50		,     output_type="np"		,     width=512		,     height=512		,     sld_guidance_scale=2_000		,     sld_warmup_steps=7		,     sld_threshold=0.025		,     sld_momentum_scale=0.5		,     sld_mom_beta=0.7		,     )

         lowerCAmelCase     :     Optional[int]								=							output.images
         lowerCAmelCase     :     Union[str, Any]								=							image[0, -3:, -3:, -1]
         lowerCAmelCase     :     int								=							np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561]						)
         assert image.shape == (1, 512, 512, 3)

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













import warnings
from contextlib import contextmanager

from ....processing_utils import ProcessorMixin
class     a    ( lowercase__   ):



      """simple docstring"""


      a  : List[str]							       =	'MCTCTFeatureExtractor'
      a  : str							       =	'AutoTokenizer'
      def __init__(      self					:			Tuple		,      __lowercase					:			int		,      __lowercase					:			Dict					)							->      Any:
        super().__init__(__lowercase		,      __lowercase					)
        __UpperCAmelCase							:	Optional[Any]           =  self.feature_extractor
        __UpperCAmelCase							:	Optional[int]           =  False
      def __call__(      self					:			int		,      *__lowercase					:			Tuple		,      **__lowercase					:			Optional[int]					)							->      Union[str, Any]:
        # For backward compatibility
        if self._in_target_context_manager:
          return self.current_processor(*__lowercase		,      **__lowercase					)

        if "raw_speech" in kwargs:
          warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."""					)
          __UpperCAmelCase							:	Dict           =  kwargs.pop("""raw_speech"""					)
        else:
          __UpperCAmelCase							:	Dict           =  kwargs.pop("""audio"""		,      __lowercase					)
        __UpperCAmelCase							:	List[str]           =  kwargs.pop("""sampling_rate"""		,      __lowercase					)
        __UpperCAmelCase							:	Tuple           =  kwargs.pop("""text"""		,      __lowercase					)
        if len(__lowercase					) > 0:
          __UpperCAmelCase							:	Tuple           =  args[0]
          __UpperCAmelCase							:	str           =  args[1:]

        if audio is None and text is None:
          raise ValueError("""You need to specify either an `audio` or `text` input to process."""					)

        if audio is not None:
          __UpperCAmelCase							:	Tuple           =  self.feature_extractor(__lowercase		,      *__lowercase		,      sampling_rate=__lowercase		,      **__lowercase					)
        if text is not None:
          __UpperCAmelCase							:	str           =  self.tokenizer(__lowercase		,      **__lowercase					)

        if text is None:
          return inputs
        elif audio is None:
          return encodings
        else:
          __UpperCAmelCase							:	Dict           =  encodings["""input_ids"""]
          return inputs
      def 	UpperCAmelCase      (      self					:			Optional[Any]		,      *__lowercase					:			List[Any]		,      **__lowercase					:			int					)							->      List[Any]:
        return self.tokenizer.batch_decode(*__lowercase		,      **__lowercase					)
      def 	UpperCAmelCase      (      self					:			Optional[int]		,      *__lowercase					:			Optional[Any]		,      **__lowercase					:			List[str]					)							->      int:
        # For backward compatibility
        if self._in_target_context_manager:
          return self.current_processor.pad(*__lowercase		,      **__lowercase					)

        __UpperCAmelCase							:	Optional[int]           =  kwargs.pop("""input_features"""		,      __lowercase					)
        __UpperCAmelCase							:	Optional[Any]           =  kwargs.pop("""labels"""		,      __lowercase					)
        if len(__lowercase					) > 0:
          __UpperCAmelCase							:	Union[str, Any]           =  args[0]
          __UpperCAmelCase							:	str           =  args[1:]

        if input_features is not None:
          __UpperCAmelCase							:	Any           =  self.feature_extractor.pad(__lowercase		,      *__lowercase		,      **__lowercase					)
        if labels is not None:
          __UpperCAmelCase							:	Union[str, Any]           =  self.tokenizer.pad(__lowercase		,      **__lowercase					)

        if labels is None:
          return input_features
        elif input_features is None:
          return labels
        else:
          __UpperCAmelCase							:	Any           =  labels["""input_ids"""]
          return input_features
      def 	UpperCAmelCase      (      self					:			Any		,      *__lowercase					:			Union[str, Any]		,      **__lowercase					:			Dict					)							->      List[Any]:
        return self.tokenizer.decode(*__lowercase		,      **__lowercase					)




      @contextmanager
      def 	UpperCAmelCase      (      self					:			Optional[Any]					)							->      Tuple:
        warnings.warn(
            """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
            """labels by using the argument `text` of the regular `__call__` method (either in the same call as """
            """your audio inputs, or in a separate call."""					)
        __UpperCAmelCase							:	Any           =  True
        __UpperCAmelCase							:	Optional[int]           =  self.tokenizer
        yield
        __UpperCAmelCase							:	List[Any]           =  self.feature_extractor
        __UpperCAmelCase							:	int           =  False


