





from typing import Any, Callable, Dict, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker


lowercase    : Any    	=  """CompVis/stable-diffusion-v1-1"""
lowercase    : Any    	=  """CompVis/stable-diffusion-v1-2"""
lowercase    : List[str]    	=  """CompVis/stable-diffusion-v1-3"""
lowercase    : str    	=  """CompVis/stable-diffusion-v1-4"""

class  __A(						__UpperCAmelCase ):

     def __init__(      self,       A,       A,       A,       A,       A,       A,       A,       A = True,       ):





            """simple docstring"""

            super()._init_()

            _UpperCamelCase              =						StableDiffusionPipeline.from_pretrained(A      )
            _UpperCamelCase              =						StableDiffusionPipeline.from_pretrained(A      )
            _UpperCamelCase              =						StableDiffusionPipeline.from_pretrained(A      )
            _UpperCamelCase              =						StableDiffusionPipeline(
                vae=A,       text_encoder=A,       tokenizer=A,       unet=A,       scheduler=A,       safety_checker=A,       feature_extractor=A,       requires_safety_checker=A,       )

            self.register_modules(pipelinea=self.pipea,       pipelinea=self.pipea,       pipelinea=self.pipea,       pipelinea=self.pipea      )

     @property
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            return {k: getattr(self,       A      ) for k in self.config.keys() if not k.startswith('''_'''      )}

     def 	_UpperCamelCase     (      self,       A = "auto"      ):





            """simple docstring"""

            if slice_size == "auto":
                   # half the attention head size is usually a good trade-off between
                   # speed and memory
                   _UpperCamelCase              =						self.unet.config.attention_head_dim // 2
            self.unet.set_attention_slice(A      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            self.enable_attention_slicing(A      )

     @torch.no_grad()
     def 	_UpperCamelCase     (      self,       A,       A = 512,       A = 512,       A = 50,       A = 7.5,       A = None,       A = 1,       A = 0.0,       A = None,       A = None,       A = "pil",       A = True,       A = None,       A = 1,       **A,       ):





            """simple docstring"""

            return self.pipea(
                prompt=A,       height=A,       width=A,       num_inference_steps=A,       guidance_scale=A,       negative_prompt=A,       num_images_per_prompt=A,       eta=A,       generator=A,       latents=A,       output_type=A,       return_dict=A,       callback=A,       callback_steps=A,       **A,       )

     @torch.no_grad()
     def 	_UpperCamelCase     (      self,       A,       A = 512,       A = 512,       A = 50,       A = 7.5,       A = None,       A = 1,       A = 0.0,       A = None,       A = None,       A = "pil",       A = True,       A = None,       A = 1,       **A,       ):





            """simple docstring"""

            return self.pipea(
                prompt=A,       height=A,       width=A,       num_inference_steps=A,       guidance_scale=A,       negative_prompt=A,       num_images_per_prompt=A,       eta=A,       generator=A,       latents=A,       output_type=A,       return_dict=A,       callback=A,       callback_steps=A,       **A,       )

     @torch.no_grad()
     def 	_UpperCamelCase     (      self,       A,       A = 512,       A = 512,       A = 50,       A = 7.5,       A = None,       A = 1,       A = 0.0,       A = None,       A = None,       A = "pil",       A = True,       A = None,       A = 1,       **A,       ):





            """simple docstring"""

            return self.pipea(
                prompt=A,       height=A,       width=A,       num_inference_steps=A,       guidance_scale=A,       negative_prompt=A,       num_images_per_prompt=A,       eta=A,       generator=A,       latents=A,       output_type=A,       return_dict=A,       callback=A,       callback_steps=A,       **A,       )

     @torch.no_grad()
     def 	_UpperCamelCase     (      self,       A,       A = 512,       A = 512,       A = 50,       A = 7.5,       A = None,       A = 1,       A = 0.0,       A = None,       A = None,       A = "pil",       A = True,       A = None,       A = 1,       **A,       ):





            """simple docstring"""

            return self.pipea(
                prompt=A,       height=A,       width=A,       num_inference_steps=A,       guidance_scale=A,       negative_prompt=A,       num_images_per_prompt=A,       eta=A,       generator=A,       latents=A,       output_type=A,       return_dict=A,       callback=A,       callback_steps=A,       **A,       )



     @torch.no_grad()
     def 	_UpperCamelCase     (      self,       A,       A = 512,       A = 512,       A = 50,       A = 7.5,       A = None,       A = 1,       A = 0.0,       A = None,       A = None,       A = "pil",       A = True,       A = None,       A = 1,       **A,       ):





            """simple docstring"""

            _UpperCamelCase              =						'''cuda''' if torch.cuda.is_available() else '''cpu'''
            self.to(A      )

            # Checks if the height and width are divisible by 8 or not
            if height % 8 != 0 or width % 8 != 0:
                   raise ValueError(F'''`height` and `width` must be divisible by 8 but are {height} and {width}.'''      )

            # Get first result from Stable Diffusion Checkpoint v1.1
            _UpperCamelCase              =						self.textaimg_sda_a(
                prompt=A,       height=A,       width=A,       num_inference_steps=A,       guidance_scale=A,       negative_prompt=A,       num_images_per_prompt=A,       eta=A,       generator=A,       latents=A,       output_type=A,       return_dict=A,       callback=A,       callback_steps=A,       **A,       )

            # Get first result from Stable Diffusion Checkpoint v1.2
            _UpperCamelCase              =						self.textaimg_sda_a(
                prompt=A,       height=A,       width=A,       num_inference_steps=A,       guidance_scale=A,       negative_prompt=A,       num_images_per_prompt=A,       eta=A,       generator=A,       latents=A,       output_type=A,       return_dict=A,       callback=A,       callback_steps=A,       **A,       )

            # Get first result from Stable Diffusion Checkpoint v1.3
            _UpperCamelCase              =						self.textaimg_sda_a(
                prompt=A,       height=A,       width=A,       num_inference_steps=A,       guidance_scale=A,       negative_prompt=A,       num_images_per_prompt=A,       eta=A,       generator=A,       latents=A,       output_type=A,       return_dict=A,       callback=A,       callback_steps=A,       **A,       )

            # Get first result from Stable Diffusion Checkpoint v1.4
            _UpperCamelCase              =						self.textaimg_sda_a(
                prompt=A,       height=A,       width=A,       num_inference_steps=A,       guidance_scale=A,       negative_prompt=A,       num_images_per_prompt=A,       eta=A,       generator=A,       latents=A,       output_type=A,       return_dict=A,       callback=A,       callback_steps=A,       **A,       )

            # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
            return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]]      )













import time
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
       import torch

       from transformers.generation import (
           MaxLengthCriteria,
           MaxNewTokensCriteria,
           MaxTimeCriteria,
           StoppingCriteriaList,
           validate_stopping_criteria,
       )

@require_torch
class  __A(						unittest.TestCase ):

     def 	_UpperCamelCase     (      self,       A      ):





            """simple docstring"""

            _UpperCamelCase              =						3
            _UpperCamelCase              =						250

            _UpperCamelCase              =						ids_tensor((batch_size, length),       A      )
            _UpperCamelCase              =						torch.ones((batch_size, length),       device=A,       dtype=torch.float      ) / length
            return input_ids, scores

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase       ,		_UpperCamelCase              =						self._get_tensors(5      )

            _UpperCamelCase              =						StoppingCriteriaList(
                [
                    MaxLengthCriteria(max_length=10      ),
                    MaxTimeCriteria(max_time=0.1      ),
                ]      )

            self.assertFalse(criteria(A,       A      )      )

            _UpperCamelCase       ,		_UpperCamelCase              =						self._get_tensors(9      )
            self.assertFalse(criteria(A,       A      )      )

            _UpperCamelCase       ,		_UpperCamelCase              =						self._get_tensors(10      )
            self.assertTrue(criteria(A,       A      )      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						MaxLengthCriteria(max_length=10      )

            _UpperCamelCase       ,		_UpperCamelCase              =						self._get_tensors(5      )
            self.assertFalse(criteria(A,       A      )      )

            _UpperCamelCase       ,		_UpperCamelCase              =						self._get_tensors(9      )
            self.assertFalse(criteria(A,       A      )      )

            _UpperCamelCase       ,		_UpperCamelCase              =						self._get_tensors(10      )
            self.assertTrue(criteria(A,       A      )      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						MaxNewTokensCriteria(start_length=5,       max_new_tokens=5      )

            _UpperCamelCase       ,		_UpperCamelCase              =						self._get_tensors(5      )
            self.assertFalse(criteria(A,       A      )      )

            _UpperCamelCase       ,		_UpperCamelCase              =						self._get_tensors(9      )
            self.assertFalse(criteria(A,       A      )      )

            _UpperCamelCase       ,		_UpperCamelCase              =						self._get_tensors(10      )
            self.assertTrue(criteria(A,       A      )      )

            _UpperCamelCase              =						StoppingCriteriaList([criteria]      )
            self.assertEqual(criteria_list.max_length,       10      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase       ,		_UpperCamelCase              =						self._get_tensors(5      )

            _UpperCamelCase              =						MaxTimeCriteria(max_time=0.1      )
            self.assertFalse(criteria(A,       A      )      )

            _UpperCamelCase              =						MaxTimeCriteria(max_time=0.1,       initial_timestamp=time.time() - 0.2      )
            self.assertTrue(criteria(A,       A      )      )



     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10      )]      ),       10      )

            with self.assertWarns(A      ):
                   validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10      )]      ),       11      )

            _UpperCamelCase              =						validate_stopping_criteria(StoppingCriteriaList(),       11      )

            self.assertEqual(len(A      ),       1      )






