






'''simple docstring'''
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


a_					= 'CompVis/stable-diffusion-v1-1'
a_					= 'CompVis/stable-diffusion-v1-2'
a_					= 'CompVis/stable-diffusion-v1-3'
a_					= 'CompVis/stable-diffusion-v1-4'






class      __SCREAMING_SNAKE_CASE      (			lowerCamelCase				):




 def __init__(      self	:							Tuple					,      __lowercase	:							AutoencoderKL					,      __lowercase	:							CLIPTextModel					,      __lowercase	:							CLIPTokenizer					,      __lowercase	:							UNetaDConditionModel					,      __lowercase	:							Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]					,      __lowercase	:							StableDiffusionSafetyChecker					,      __lowercase	:							CLIPImageProcessor					,      __lowercase	:							bool = True					,      )	->						List[str]:
       super()._init_()

       SCREAMING_SNAKE_CASE__     :				str									=StableDiffusionPipeline.from_pretrained(__lowercase      )
       SCREAMING_SNAKE_CASE__     :				Any									=StableDiffusionPipeline.from_pretrained(__lowercase      )
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=StableDiffusionPipeline.from_pretrained(__lowercase      )
       SCREAMING_SNAKE_CASE__     :				List[Any]									=StableDiffusionPipeline(
           vae=__lowercase					,      text_encoder=__lowercase					,      tokenizer=__lowercase					,      unet=__lowercase					,      scheduler=__lowercase					,      safety_checker=__lowercase					,      feature_extractor=__lowercase					,      requires_safety_checker=__lowercase					,      )

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




 @property
 def      __magic_name__	(      self	:							Optional[Any]      )	->						Dict[str, Any]:
       return {k: getattr(self					,      __lowercase      ) for k in self.config.keys() if not k.startswith('''_'''      )}




 def      __magic_name__	(      self	:							List[Any]					,      __lowercase	:							Optional[Union[str, int]] = "auto"      )	->						Any:
       if slice_size == "auto":
             # half the attention head size is usually a good trade-off between
             # speed and memory
             SCREAMING_SNAKE_CASE__     :				str									=self.unet.config.attention_head_dim // 2
       self.unet.set_attention_slice(__lowercase      )




 def      __magic_name__	(      self	:							Union[str, Any]      )	->						int:
       self.enable_attention_slicing(__lowercase      )




 @torch.no_grad()
 def      __magic_name__	(      self	:							Optional[Any]					,      __lowercase	:							Union[str, List[str]]					,      __lowercase	:							int = 5_12					,      __lowercase	:							int = 5_12					,      __lowercase	:							int = 50					,      __lowercase	:							float = 7.5					,      __lowercase	:							Optional[Union[str, List[str]]] = None					,      __lowercase	:							Optional[int] = 1					,      __lowercase	:							float = 0.0					,      __lowercase	:							Optional[torch.Generator] = None					,      __lowercase	:							Optional[torch.FloatTensor] = None					,      __lowercase	:							Optional[str] = "pil"					,      __lowercase	:							bool = True					,      __lowercase	:							Optional[Callable[[int, int, torch.FloatTensor], None]] = None					,      __lowercase	:							int = 1					,      **__lowercase	:							Optional[Any]					,      )	->						Optional[int]:
       return self.pipea(
           prompt=__lowercase					,      height=__lowercase					,      width=__lowercase					,      num_inference_steps=__lowercase					,      guidance_scale=__lowercase					,      negative_prompt=__lowercase					,      num_images_per_prompt=__lowercase					,      eta=__lowercase					,      generator=__lowercase					,      latents=__lowercase					,      output_type=__lowercase					,      return_dict=__lowercase					,      callback=__lowercase					,      callback_steps=__lowercase					,      **__lowercase					,      )




 @torch.no_grad()
 def      __magic_name__	(      self	:							Any					,      __lowercase	:							Union[str, List[str]]					,      __lowercase	:							int = 5_12					,      __lowercase	:							int = 5_12					,      __lowercase	:							int = 50					,      __lowercase	:							float = 7.5					,      __lowercase	:							Optional[Union[str, List[str]]] = None					,      __lowercase	:							Optional[int] = 1					,      __lowercase	:							float = 0.0					,      __lowercase	:							Optional[torch.Generator] = None					,      __lowercase	:							Optional[torch.FloatTensor] = None					,      __lowercase	:							Optional[str] = "pil"					,      __lowercase	:							bool = True					,      __lowercase	:							Optional[Callable[[int, int, torch.FloatTensor], None]] = None					,      __lowercase	:							int = 1					,      **__lowercase	:							List[str]					,      )	->						List[str]:
       return self.pipea(
           prompt=__lowercase					,      height=__lowercase					,      width=__lowercase					,      num_inference_steps=__lowercase					,      guidance_scale=__lowercase					,      negative_prompt=__lowercase					,      num_images_per_prompt=__lowercase					,      eta=__lowercase					,      generator=__lowercase					,      latents=__lowercase					,      output_type=__lowercase					,      return_dict=__lowercase					,      callback=__lowercase					,      callback_steps=__lowercase					,      **__lowercase					,      )




 @torch.no_grad()
 def      __magic_name__	(      self	:							Dict					,      __lowercase	:							Union[str, List[str]]					,      __lowercase	:							int = 5_12					,      __lowercase	:							int = 5_12					,      __lowercase	:							int = 50					,      __lowercase	:							float = 7.5					,      __lowercase	:							Optional[Union[str, List[str]]] = None					,      __lowercase	:							Optional[int] = 1					,      __lowercase	:							float = 0.0					,      __lowercase	:							Optional[torch.Generator] = None					,      __lowercase	:							Optional[torch.FloatTensor] = None					,      __lowercase	:							Optional[str] = "pil"					,      __lowercase	:							bool = True					,      __lowercase	:							Optional[Callable[[int, int, torch.FloatTensor], None]] = None					,      __lowercase	:							int = 1					,      **__lowercase	:							Any					,      )	->						List[Any]:
       return self.pipea(
           prompt=__lowercase					,      height=__lowercase					,      width=__lowercase					,      num_inference_steps=__lowercase					,      guidance_scale=__lowercase					,      negative_prompt=__lowercase					,      num_images_per_prompt=__lowercase					,      eta=__lowercase					,      generator=__lowercase					,      latents=__lowercase					,      output_type=__lowercase					,      return_dict=__lowercase					,      callback=__lowercase					,      callback_steps=__lowercase					,      **__lowercase					,      )




 @torch.no_grad()
 def      __magic_name__	(      self	:							Optional[Any]					,      __lowercase	:							Union[str, List[str]]					,      __lowercase	:							int = 5_12					,      __lowercase	:							int = 5_12					,      __lowercase	:							int = 50					,      __lowercase	:							float = 7.5					,      __lowercase	:							Optional[Union[str, List[str]]] = None					,      __lowercase	:							Optional[int] = 1					,      __lowercase	:							float = 0.0					,      __lowercase	:							Optional[torch.Generator] = None					,      __lowercase	:							Optional[torch.FloatTensor] = None					,      __lowercase	:							Optional[str] = "pil"					,      __lowercase	:							bool = True					,      __lowercase	:							Optional[Callable[[int, int, torch.FloatTensor], None]] = None					,      __lowercase	:							int = 1					,      **__lowercase	:							Optional[Any]					,      )	->						Tuple:
       return self.pipea(
           prompt=__lowercase					,      height=__lowercase					,      width=__lowercase					,      num_inference_steps=__lowercase					,      guidance_scale=__lowercase					,      negative_prompt=__lowercase					,      num_images_per_prompt=__lowercase					,      eta=__lowercase					,      generator=__lowercase					,      latents=__lowercase					,      output_type=__lowercase					,      return_dict=__lowercase					,      callback=__lowercase					,      callback_steps=__lowercase					,      **__lowercase					,      )




 @torch.no_grad()
 def      __magic_name__	(      self	:							int					,      __lowercase	:							Union[str, List[str]]					,      __lowercase	:							int = 5_12					,      __lowercase	:							int = 5_12					,      __lowercase	:							int = 50					,      __lowercase	:							float = 7.5					,      __lowercase	:							Optional[Union[str, List[str]]] = None					,      __lowercase	:							Optional[int] = 1					,      __lowercase	:							float = 0.0					,      __lowercase	:							Optional[torch.Generator] = None					,      __lowercase	:							Optional[torch.FloatTensor] = None					,      __lowercase	:							Optional[str] = "pil"					,      __lowercase	:							bool = True					,      __lowercase	:							Optional[Callable[[int, int, torch.FloatTensor], None]] = None					,      __lowercase	:							int = 1					,      **__lowercase	:							Optional[int]					,      )	->						Dict:
       SCREAMING_SNAKE_CASE__     :				Tuple									='''cuda''' if torch.cuda.is_available() else '''cpu'''
       self.to(__lowercase      )

       # 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
       SCREAMING_SNAKE_CASE__     :				Any									=self.textaimg_sda_a(
           prompt=__lowercase					,      height=__lowercase					,      width=__lowercase					,      num_inference_steps=__lowercase					,      guidance_scale=__lowercase					,      negative_prompt=__lowercase					,      num_images_per_prompt=__lowercase					,      eta=__lowercase					,      generator=__lowercase					,      latents=__lowercase					,      output_type=__lowercase					,      return_dict=__lowercase					,      callback=__lowercase					,      callback_steps=__lowercase					,      **__lowercase					,      )

       # Get first result from Stable Diffusion Checkpoint v1.2
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=self.textaimg_sda_a(
           prompt=__lowercase					,      height=__lowercase					,      width=__lowercase					,      num_inference_steps=__lowercase					,      guidance_scale=__lowercase					,      negative_prompt=__lowercase					,      num_images_per_prompt=__lowercase					,      eta=__lowercase					,      generator=__lowercase					,      latents=__lowercase					,      output_type=__lowercase					,      return_dict=__lowercase					,      callback=__lowercase					,      callback_steps=__lowercase					,      **__lowercase					,      )

       # Get first result from Stable Diffusion Checkpoint v1.3
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=self.textaimg_sda_a(
           prompt=__lowercase					,      height=__lowercase					,      width=__lowercase					,      num_inference_steps=__lowercase					,      guidance_scale=__lowercase					,      negative_prompt=__lowercase					,      num_images_per_prompt=__lowercase					,      eta=__lowercase					,      generator=__lowercase					,      latents=__lowercase					,      output_type=__lowercase					,      return_dict=__lowercase					,      callback=__lowercase					,      callback_steps=__lowercase					,      **__lowercase					,      )

       # Get first result from Stable Diffusion Checkpoint v1.4
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=self.textaimg_sda_a(
           prompt=__lowercase					,      height=__lowercase					,      width=__lowercase					,      num_inference_steps=__lowercase					,      guidance_scale=__lowercase					,      negative_prompt=__lowercase					,      num_images_per_prompt=__lowercase					,      eta=__lowercase					,      generator=__lowercase					,      latents=__lowercase					,      output_type=__lowercase					,      return_dict=__lowercase					,      callback=__lowercase					,      callback_steps=__lowercase					,      **__lowercase					,      )

       # 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]]      )







'''simple docstring'''
import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
  from PIL import Image
else:






  class      __SCREAMING_SNAKE_CASE      :




   @staticmethod
   def      __magic_name__	(      *__lowercase	:							int					,      **__lowercase	:							Optional[Any]      )	->						Optional[Any]:
         pass






@is_pipeline_test
@require_vision
class      __SCREAMING_SNAKE_CASE      (			unittest.TestCase				):




 @require_torch
 def      __magic_name__	(      self	:							Optional[int]      )	->						Tuple:
       SCREAMING_SNAKE_CASE__     :				List[Any]									=pipeline(
           model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification'''					,      )
       SCREAMING_SNAKE_CASE__     :				List[str]									=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
       SCREAMING_SNAKE_CASE__     :				Any									=image_classifier(__lowercase					,      candidate_labels=['''a''', '''b''', '''c''']      )

       # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
       # python and torch versions.
       self.assertIn(
           nested_simplify(__lowercase      )					,      [
               [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}],
               [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}],
           ]					,      )

       SCREAMING_SNAKE_CASE__     :				int									=image_classifier([image] * 5					,      candidate_labels=['''A''', '''B''', '''C''']					,      batch_size=2      )
       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
           ]					,      )




 @require_tf
 def      __magic_name__	(      self	:							Union[str, Any]      )	->						Optional[int]:
       SCREAMING_SNAKE_CASE__     :				List[Any]									=pipeline(
           model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification'''					,      framework='''tf'''      )
       SCREAMING_SNAKE_CASE__     :				Dict									=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
       SCREAMING_SNAKE_CASE__     :				Tuple									=image_classifier(__lowercase					,      candidate_labels=['''a''', '''b''', '''c''']      )

       self.assertEqual(
           nested_simplify(__lowercase      )					,      [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}]					,      )

       SCREAMING_SNAKE_CASE__     :				List[Any]									=image_classifier([image] * 5					,      candidate_labels=['''A''', '''B''', '''C''']					,      batch_size=2      )
       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
           ]					,      )




 @slow
 @require_torch
 def      __magic_name__	(      self	:							List[Any]      )	->						Dict:
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=pipeline(
           task='''zero-shot-image-classification'''					,      model='''openai/clip-vit-base-patch32'''					,      )
       # This is an image of 2 cats with remotes and no planes
       SCREAMING_SNAKE_CASE__     :				Any									=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
       SCREAMING_SNAKE_CASE__     :				List[str]									=image_classifier(__lowercase					,      candidate_labels=['''cat''', '''plane''', '''remote''']      )

       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               {'''score''': 0.511, '''label''': '''remote'''},
               {'''score''': 0.485, '''label''': '''cat'''},
               {'''score''': 0.004, '''label''': '''plane'''},
           ]					,      )

       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=image_classifier([image] * 5					,      candidate_labels=['''cat''', '''plane''', '''remote''']					,      batch_size=2      )
       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               [
                   {'''score''': 0.511, '''label''': '''remote'''},
                   {'''score''': 0.485, '''label''': '''cat'''},
                   {'''score''': 0.004, '''label''': '''plane'''},
               ],
           ]
           * 5					,      )




 @slow
 @require_tf
 def      __magic_name__	(      self	:							Union[str, Any]      )	->						int:
       SCREAMING_SNAKE_CASE__     :				str									=pipeline(
           task='''zero-shot-image-classification'''					,      model='''openai/clip-vit-base-patch32'''					,      framework='''tf'''      )
       # This is an image of 2 cats with remotes and no planes
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
       SCREAMING_SNAKE_CASE__     :				Any									=image_classifier(__lowercase					,      candidate_labels=['''cat''', '''plane''', '''remote''']      )
       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               {'''score''': 0.511, '''label''': '''remote'''},
               {'''score''': 0.485, '''label''': '''cat'''},
               {'''score''': 0.004, '''label''': '''plane'''},
           ]					,      )

       SCREAMING_SNAKE_CASE__     :				List[Any]									=image_classifier([image] * 5					,      candidate_labels=['''cat''', '''plane''', '''remote''']					,      batch_size=2      )
       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               [
                   {'''score''': 0.511, '''label''': '''remote'''},
                   {'''score''': 0.485, '''label''': '''cat'''},
                   {'''score''': 0.004, '''label''': '''plane'''},
               ],
           ]
           * 5					,      )