





from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import MagicMock, patch

from transformers import AutoModel, TFAutoModel
from transformers.onnx import FeaturesManager
from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch
@require_torch
@require_tf
class 							SCREAMING_SNAKE_CASE  (UpperCAmelCase_ ):


   def 			SCREAMING_SNAKE_CASE_				(       self     :							int			)->  Union[str, Any]:





     """simple docstring"""







     lowercase__           =    SMALL_MODEL_IDENTIFIER
     lowercase__           =    """pt"""
     lowercase__           =    """tf"""


   def 			SCREAMING_SNAKE_CASE_				(       self     :							Dict     ,	a     :							int			)->  List[Any]:





     """simple docstring"""







     lowercase__           =    AutoModel.from_pretrained(self.test_model			)
     model_pt.save_pretrained(lowerCamelCase__			)


   def 			SCREAMING_SNAKE_CASE_				(       self     :							Tuple     ,	a     :							Union[str, Any]			)->  Dict:





     """simple docstring"""







     lowercase__           =    TFAutoModel.from_pretrained(self.test_model     ,	from_pt=lowerCamelCase__			)
     model_tf.save_pretrained(lowerCamelCase__			)


   def 			SCREAMING_SNAKE_CASE_				(       self     :							List[str]			)->  Tuple:





     """simple docstring"""







     lowercase__           =    """mock_framework"""

     # Framework provided - return whatever the user provides
     lowercase__           =    FeaturesManager.determine_framework(self.test_model     ,	lowerCamelCase__			)
     self.assertEqual(lowerCamelCase__     ,	lowerCamelCase__			)

     # Local checkpoint and framework provided - return provided framework
     # PyTorch checkpoint
     with TemporaryDirectory() as local_pt_ckpt:
       self._setup_pt_ckpt(lowerCamelCase__			)
       lowercase__           =    FeaturesManager.determine_framework(lowerCamelCase__     ,	lowerCamelCase__			)
       self.assertEqual(lowerCamelCase__     ,	lowerCamelCase__			)

     # TensorFlow checkpoint
     with TemporaryDirectory() as local_tf_ckpt:
       self._setup_tf_ckpt(lowerCamelCase__			)
       lowercase__           =    FeaturesManager.determine_framework(lowerCamelCase__     ,	lowerCamelCase__			)
       self.assertEqual(lowerCamelCase__     ,	lowerCamelCase__			)


   def 			SCREAMING_SNAKE_CASE_				(       self     :							Optional[int]			)->  int:





     """simple docstring"""







     with TemporaryDirectory() as local_pt_ckpt:
       self._setup_pt_ckpt(lowerCamelCase__			)
       lowercase__           =    FeaturesManager.determine_framework(lowerCamelCase__			)
       self.assertEqual(lowerCamelCase__     ,	self.framework_pt			)

     # TensorFlow checkpoint
     with TemporaryDirectory() as local_tf_ckpt:
       self._setup_tf_ckpt(lowerCamelCase__			)
       lowercase__           =    FeaturesManager.determine_framework(lowerCamelCase__			)
       self.assertEqual(lowerCamelCase__     ,	self.framework_tf			)

     # Invalid local checkpoint
     with TemporaryDirectory() as local_invalid_ckpt:
       with self.assertRaises(lowerCamelCase__			):
         lowercase__           =    FeaturesManager.determine_framework(lowerCamelCase__			)


   def 			SCREAMING_SNAKE_CASE_				(       self     :							List[Any]			)->  Any:





     """simple docstring"""







     lowercase__           =    MagicMock(return_value=lowerCamelCase__			)
     with patch('transformers.onnx.features.is_tf_available'     ,	lowerCamelCase__			):
       lowercase__           =    FeaturesManager.determine_framework(self.test_model			)
       self.assertEqual(lowerCamelCase__     ,	self.framework_pt			)

     # PyTorch not in environment -> use TensorFlow
     lowercase__           =    MagicMock(return_value=lowerCamelCase__			)
     with patch('transformers.onnx.features.is_torch_available'     ,	lowerCamelCase__			):
       lowercase__           =    FeaturesManager.determine_framework(self.test_model			)
       self.assertEqual(lowerCamelCase__     ,	self.framework_tf			)

     # Both in environment -> use PyTorch
     lowercase__           =    MagicMock(return_value=lowerCamelCase__			)
     lowercase__           =    MagicMock(return_value=lowerCamelCase__			)
     with patch('transformers.onnx.features.is_tf_available'     ,	lowerCamelCase__			), patch(
         'transformers.onnx.features.is_torch_available'     ,	lowerCamelCase__			):
       lowercase__           =    FeaturesManager.determine_framework(self.test_model			)
       self.assertEqual(lowerCamelCase__     ,	self.framework_pt			)

     # Both not in environment -> raise error
     lowercase__           =    MagicMock(return_value=lowerCamelCase__			)
     lowercase__           =    MagicMock(return_value=lowerCamelCase__			)
     with patch('transformers.onnx.features.is_tf_available'     ,	lowerCamelCase__			), patch(
         'transformers.onnx.features.is_torch_available'     ,	lowerCamelCase__			):
       with self.assertRaises(lowerCamelCase__			):
         lowercase__           =    FeaturesManager.determine_framework(self.test_model			)










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


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







class 		_A						( UpperCAmelCase_ ):

  def __init__(    self						:	List[str]   ,				lowerCamelCase__						:	AutoencoderKL   ,				lowerCamelCase__						:	CLIPTextModel   ,				lowerCamelCase__						:	CLIPTokenizer   ,				lowerCamelCase__						:	UNetaDConditionModel   ,				lowerCamelCase__						:	Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]   ,				lowerCamelCase__						:	StableDiffusionSafetyChecker   ,				lowerCamelCase__						:	CLIPImageProcessor   ,				lowerCamelCase__						:	bool = True   ,				):
     """simple docstring"""

     super()._init_()

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

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

  @property
  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

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

  def    a					(    self						:	List[str]   ,				lowerCamelCase__						:	Optional[Union[str, int]] = "auto"			):
     """simple docstring"""

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

  def    a					(    self						:	str			):
     """simple docstring"""

     self.enable_attention_slicing(lowerCamelCase__			)

  @torch.no_grad()
  def    a					(    self						:	Any   ,				lowerCamelCase__						:	Union[str, List[str]]   ,				lowerCamelCase__						:	int = 5_12   ,				lowerCamelCase__						:	int = 5_12   ,				lowerCamelCase__						:	int = 50   ,				lowerCamelCase__						:	float = 7.5   ,				lowerCamelCase__						:	Optional[Union[str, List[str]]] = None   ,				lowerCamelCase__						:	Optional[int] = 1   ,				lowerCamelCase__						:	float = 0.0   ,				lowerCamelCase__						:	Optional[torch.Generator] = None   ,				lowerCamelCase__						:	Optional[torch.FloatTensor] = None   ,				lowerCamelCase__						:	Optional[str] = "pil"   ,				lowerCamelCase__						:	bool = True   ,				lowerCamelCase__						:	Optional[Callable[[int, int, torch.FloatTensor], None]] = None   ,				lowerCamelCase__						:	int = 1   ,				**lowerCamelCase__						:	str   ,				):
     """simple docstring"""

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

  @torch.no_grad()
  def    a					(    self						:	Union[str, Any]   ,				lowerCamelCase__						:	Union[str, List[str]]   ,				lowerCamelCase__						:	int = 5_12   ,				lowerCamelCase__						:	int = 5_12   ,				lowerCamelCase__						:	int = 50   ,				lowerCamelCase__						:	float = 7.5   ,				lowerCamelCase__						:	Optional[Union[str, List[str]]] = None   ,				lowerCamelCase__						:	Optional[int] = 1   ,				lowerCamelCase__						:	float = 0.0   ,				lowerCamelCase__						:	Optional[torch.Generator] = None   ,				lowerCamelCase__						:	Optional[torch.FloatTensor] = None   ,				lowerCamelCase__						:	Optional[str] = "pil"   ,				lowerCamelCase__						:	bool = True   ,				lowerCamelCase__						:	Optional[Callable[[int, int, torch.FloatTensor], None]] = None   ,				lowerCamelCase__						:	int = 1   ,				**lowerCamelCase__						:	Dict   ,				):
     """simple docstring"""

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

  @torch.no_grad()
  def    a					(    self						:	Union[str, Any]   ,				lowerCamelCase__						:	Union[str, List[str]]   ,				lowerCamelCase__						:	int = 5_12   ,				lowerCamelCase__						:	int = 5_12   ,				lowerCamelCase__						:	int = 50   ,				lowerCamelCase__						:	float = 7.5   ,				lowerCamelCase__						:	Optional[Union[str, List[str]]] = None   ,				lowerCamelCase__						:	Optional[int] = 1   ,				lowerCamelCase__						:	float = 0.0   ,				lowerCamelCase__						:	Optional[torch.Generator] = None   ,				lowerCamelCase__						:	Optional[torch.FloatTensor] = None   ,				lowerCamelCase__						:	Optional[str] = "pil"   ,				lowerCamelCase__						:	bool = True   ,				lowerCamelCase__						:	Optional[Callable[[int, int, torch.FloatTensor], None]] = None   ,				lowerCamelCase__						:	int = 1   ,				**lowerCamelCase__						:	Any   ,				):
     """simple docstring"""

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

  @torch.no_grad()
  def    a					(    self						:	Dict   ,				lowerCamelCase__						:	Union[str, List[str]]   ,				lowerCamelCase__						:	int = 5_12   ,				lowerCamelCase__						:	int = 5_12   ,				lowerCamelCase__						:	int = 50   ,				lowerCamelCase__						:	float = 7.5   ,				lowerCamelCase__						:	Optional[Union[str, List[str]]] = None   ,				lowerCamelCase__						:	Optional[int] = 1   ,				lowerCamelCase__						:	float = 0.0   ,				lowerCamelCase__						:	Optional[torch.Generator] = None   ,				lowerCamelCase__						:	Optional[torch.FloatTensor] = None   ,				lowerCamelCase__						:	Optional[str] = "pil"   ,				lowerCamelCase__						:	bool = True   ,				lowerCamelCase__						:	Optional[Callable[[int, int, torch.FloatTensor], None]] = None   ,				lowerCamelCase__						:	int = 1   ,				**lowerCamelCase__						:	List[Any]   ,				):
     """simple docstring"""

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

  @torch.no_grad()
  def    a					(    self						:	Optional[Any]   ,				lowerCamelCase__						:	Union[str, List[str]]   ,				lowerCamelCase__						:	int = 5_12   ,				lowerCamelCase__						:	int = 5_12   ,				lowerCamelCase__						:	int = 50   ,				lowerCamelCase__						:	float = 7.5   ,				lowerCamelCase__						:	Optional[Union[str, List[str]]] = None   ,				lowerCamelCase__						:	Optional[int] = 1   ,				lowerCamelCase__						:	float = 0.0   ,				lowerCamelCase__						:	Optional[torch.Generator] = None   ,				lowerCamelCase__						:	Optional[torch.FloatTensor] = None   ,				lowerCamelCase__						:	Optional[str] = "pil"   ,				lowerCamelCase__						:	bool = True   ,				lowerCamelCase__						:	Optional[Callable[[int, int, torch.FloatTensor], None]] = None   ,				lowerCamelCase__						:	int = 1   ,				**lowerCamelCase__						:	Dict   ,				):
     """simple docstring"""

     __UpperCamelCase	:			Optional[Any]					=					"""cuda""" if torch.cuda.is_available() else """cpu"""
     self.to(lowerCamelCase__			)

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

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

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

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

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



