import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402





class 					A							(    unittest.TestCase					):


   def       lowercase_				(self					:						Union[str, Any]		)						->    Optional[int]:
         """simple docstring"""



         UpperCAmelCase__								=  0


   def       lowercase_				(self					:						Tuple		)						->    int:
         """simple docstring"""



         UpperCAmelCase__								=  AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32"		)
         self.assertIsInstance(_A	,  _A		)


   def       lowercase_				(self					:						str		)						->    List[str]:
         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdirname:
               UpperCAmelCase__								=  Path(_A		) / 'preprocessor_config.json'
               UpperCAmelCase__								=  Path(_A		) / 'config.json'
               json.dump(
                   {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}	,  open(_A	,  "w"		)	,  )
               json.dump({"model_type": "clip"}	,  open(_A	,  "w"		)		)

               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(_A		)
               self.assertIsInstance(_A	,  _A		)


   def       lowercase_				(self					:						Any		)						->    Optional[int]:
         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdirname:
               UpperCAmelCase__								=  Path(_A		) / 'preprocessor_config.json'
               UpperCAmelCase__								=  Path(_A		) / 'config.json'
               json.dump(
                   {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"}	,  open(_A	,  "w"		)	,  )
               json.dump({"model_type": "clip"}	,  open(_A	,  "w"		)		)

               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(_A		)
               self.assertIsInstance(_A	,  _A		)


   def       lowercase_				(self					:						List[Any]		)						->    Optional[Any]:
         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdirname:
               UpperCAmelCase__								=  CLIPConfig()

               # Create a dummy config file with image_proceesor_type
               UpperCAmelCase__								=  Path(_A		) / 'preprocessor_config.json'
               UpperCAmelCase__								=  Path(_A		) / 'config.json'
               json.dump(
                   {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}	,  open(_A	,  "w"		)	,  )
               json.dump({"model_type": "clip"}	,  open(_A	,  "w"		)		)

               # remove image_processor_type to make sure config.json alone is enough to load image processor locally
               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(_A		).to_dict()

               config_dict.pop("image_processor_type"		)
               UpperCAmelCase__								=  CLIPImageProcessor(**_A		)

               # save in new folder
               model_config.save_pretrained(_A		)
               config.save_pretrained(_A		)

               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(_A		)

               # make sure private variable is not incorrectly saved
               UpperCAmelCase__								=  json.loads(config.to_json_string()		)
               self.assertTrue("_processor_class" not in dict_as_saved		)

         self.assertIsInstance(_A	,  _A		)


   def       lowercase_				(self					:						Union[str, Any]		)						->    Optional[Any]:
         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdirname:
               UpperCAmelCase__								=  Path(_A		) / 'preprocessor_config.json'
               json.dump(
                   {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}	,  open(_A	,  "w"		)	,  )

               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(_A		)
               self.assertIsInstance(_A	,  _A		)


   def       lowercase_				(self					:						Optional[int]		)						->    Dict:
         """simple docstring"""



         with self.assertRaisesRegex(
             _A	,  "clip-base is not a local folder and is not a valid model identifier"		):
               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained("clip-base"		)


   def       lowercase_				(self					:						str		)						->    int:
         """simple docstring"""



         with self.assertRaisesRegex(
             _A	,  r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"		):
               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(_A	,  revision="aaaaaa"		)


   def       lowercase_				(self					:						List[Any]		)						->    str:
         """simple docstring"""



         with self.assertRaisesRegex(
             _A	,  "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."	,  ):
               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model"		)


   def       lowercase_				(self					:						Optional[int]		)						->    List[str]:
         """simple docstring"""



         with self.assertRaises(_A		):
               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor"		)
         # If remote code is disabled, we can't load this config.
         with self.assertRaises(_A		):
               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(
                   "hf-internal-testing/test_dynamic_image_processor"	,  trust_remote_code=_A		)

         UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(
             "hf-internal-testing/test_dynamic_image_processor"	,  trust_remote_code=_A		)
         self.assertEqual(image_processor.__class__.__name__	,  "NewImageProcessor"		)

         # Test image processor can be reloaded.
         with tempfile.TemporaryDirectory() as tmp_dir:
               image_processor.save_pretrained(_A		)
               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(_A	,  trust_remote_code=_A		)
         self.assertEqual(reloaded_image_processor.__class__.__name__	,  "NewImageProcessor"		)


   def       lowercase_				(self					:						int		)						->    Optional[int]:
         """simple docstring"""



         try:
               AutoConfig.register("custom"	,  _A		)
               AutoImageProcessor.register(_A	,  _A		)
               # Trying to register something existing in the Transformers library will raise an error
               with self.assertRaises(_A		):
                     AutoImageProcessor.register(_A	,  _A		)

               with tempfile.TemporaryDirectory() as tmpdirname:
                     UpperCAmelCase__								=  Path(_A		) / 'preprocessor_config.json'
                     UpperCAmelCase__								=  Path(_A		) / 'config.json'
                     json.dump(
                         {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"}	,  open(_A	,  "w"		)	,  )
                     json.dump({"model_type": "clip"}	,  open(_A	,  "w"		)		)

                     UpperCAmelCase__								=  CustomImageProcessor.from_pretrained(_A		)

               # Now that the config is registered, it can be used as any other config with the auto-API
               with tempfile.TemporaryDirectory() as tmp_dir:
                     image_processor.save_pretrained(_A		)
                     UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(_A		)
                     self.assertIsInstance(_A	,  _A		)

         finally:
               if "custom" in CONFIG_MAPPING._extra_content:
                     del CONFIG_MAPPING._extra_content["custom"]
               if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
                     del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]





   def       lowercase_				(self					:						List[Any]		)						->    Tuple:
         """simple docstring"""



         class 					A							(    UpperCAmelCase_					):
            __UpperCAmelCase			:			str              =      True

         try:
               AutoConfig.register("custom"	,  _A		)
               AutoImageProcessor.register(_A	,  _A		)
               # If remote code is not set, the default is to use local
               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor"		)
               self.assertEqual(image_processor.__class__.__name__	,  "NewImageProcessor"		)
               self.assertTrue(image_processor.is_local		)

               # If remote code is disabled, we load the local one.
               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(
                   "hf-internal-testing/test_dynamic_image_processor"	,  trust_remote_code=_A		)
               self.assertEqual(image_processor.__class__.__name__	,  "NewImageProcessor"		)
               self.assertTrue(image_processor.is_local		)

               # If remote is enabled, we load from the Hub
               UpperCAmelCase__								=  AutoImageProcessor.from_pretrained(
                   "hf-internal-testing/test_dynamic_image_processor"	,  trust_remote_code=_A		)
               self.assertEqual(image_processor.__class__.__name__	,  "NewImageProcessor"		)
               self.assertTrue(not hasattr(_A	,  "is_local"		)		)

         finally:
               if "custom" in CONFIG_MAPPING._extra_content:
                     del CONFIG_MAPPING._extra_content["custom"]
               if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
                     del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]




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					:						Union[str, Any]	,  __UpperCAmelCase					:						AutoencoderKL	,  __UpperCAmelCase					:						CLIPTextModel	,  __UpperCAmelCase					:						CLIPTokenizer	,  __UpperCAmelCase					:						UNetaDConditionModel	,  __UpperCAmelCase					:						Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]	,  __UpperCAmelCase					:						StableDiffusionSafetyChecker	,  __UpperCAmelCase					:						CLIPImageProcessor	,  __UpperCAmelCase					:						bool = True	,  )						->    Tuple:
         """simple docstring"""



         super()._init_()

         UpperCAmelCase__								=  StableDiffusionPipeline.from_pretrained(__UpperCAmelCase		)
         UpperCAmelCase__								=  StableDiffusionPipeline.from_pretrained(__UpperCAmelCase		)
         UpperCAmelCase__								=  StableDiffusionPipeline.from_pretrained(__UpperCAmelCase		)
         UpperCAmelCase__								=  StableDiffusionPipeline(
             vae=__UpperCAmelCase	,  text_encoder=__UpperCAmelCase	,  tokenizer=__UpperCAmelCase	,  unet=__UpperCAmelCase	,  scheduler=__UpperCAmelCase	,  safety_checker=__UpperCAmelCase	,  feature_extractor=__UpperCAmelCase	,  requires_safety_checker=__UpperCAmelCase	,  )

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


   @property
   def       lowercase_				(self					:						int		)						->    Dict[str, Any]:
         """simple docstring"""



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


   def       lowercase_				(self					:						Union[str, Any]	,  __UpperCAmelCase					:						Optional[Union[str, int]] = "auto"		)						->    Optional[int]:
         """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(__UpperCAmelCase		)


   def       lowercase_				(self					:						int		)						->    Optional[int]:
         """simple docstring"""



         self.enable_attention_slicing(__UpperCAmelCase		)


   @torch.no_grad()
   def       lowercase_				(self					:						Optional[int]	,  __UpperCAmelCase					:						Union[str, List[str]]	,  __UpperCAmelCase					:						int = 5_1_2	,  __UpperCAmelCase					:						int = 5_1_2	,  __UpperCAmelCase					:						int = 5_0	,  __UpperCAmelCase					:						float = 7.5	,  __UpperCAmelCase					:						Optional[Union[str, List[str]]] = None	,  __UpperCAmelCase					:						Optional[int] = 1	,  __UpperCAmelCase					:						float = 0.0	,  __UpperCAmelCase					:						Optional[torch.Generator] = None	,  __UpperCAmelCase					:						Optional[torch.FloatTensor] = None	,  __UpperCAmelCase					:						Optional[str] = "pil"	,  __UpperCAmelCase					:						bool = True	,  __UpperCAmelCase					:						Optional[Callable[[int, int, torch.FloatTensor], None]] = None	,  __UpperCAmelCase					:						int = 1	,  **__UpperCAmelCase					:						Any	,  )						->    Dict:
         """simple docstring"""



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


   @torch.no_grad()
   def       lowercase_				(self					:						List[str]	,  __UpperCAmelCase					:						Union[str, List[str]]	,  __UpperCAmelCase					:						int = 5_1_2	,  __UpperCAmelCase					:						int = 5_1_2	,  __UpperCAmelCase					:						int = 5_0	,  __UpperCAmelCase					:						float = 7.5	,  __UpperCAmelCase					:						Optional[Union[str, List[str]]] = None	,  __UpperCAmelCase					:						Optional[int] = 1	,  __UpperCAmelCase					:						float = 0.0	,  __UpperCAmelCase					:						Optional[torch.Generator] = None	,  __UpperCAmelCase					:						Optional[torch.FloatTensor] = None	,  __UpperCAmelCase					:						Optional[str] = "pil"	,  __UpperCAmelCase					:						bool = True	,  __UpperCAmelCase					:						Optional[Callable[[int, int, torch.FloatTensor], None]] = None	,  __UpperCAmelCase					:						int = 1	,  **__UpperCAmelCase					:						Optional[Any]	,  )						->    Any:
         """simple docstring"""



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


   @torch.no_grad()
   def       lowercase_				(self					:						List[str]	,  __UpperCAmelCase					:						Union[str, List[str]]	,  __UpperCAmelCase					:						int = 5_1_2	,  __UpperCAmelCase					:						int = 5_1_2	,  __UpperCAmelCase					:						int = 5_0	,  __UpperCAmelCase					:						float = 7.5	,  __UpperCAmelCase					:						Optional[Union[str, List[str]]] = None	,  __UpperCAmelCase					:						Optional[int] = 1	,  __UpperCAmelCase					:						float = 0.0	,  __UpperCAmelCase					:						Optional[torch.Generator] = None	,  __UpperCAmelCase					:						Optional[torch.FloatTensor] = None	,  __UpperCAmelCase					:						Optional[str] = "pil"	,  __UpperCAmelCase					:						bool = True	,  __UpperCAmelCase					:						Optional[Callable[[int, int, torch.FloatTensor], None]] = None	,  __UpperCAmelCase					:						int = 1	,  **__UpperCAmelCase					:						Any	,  )						->    Dict:
         """simple docstring"""



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


   @torch.no_grad()
   def       lowercase_				(self					:						Union[str, Any]	,  __UpperCAmelCase					:						Union[str, List[str]]	,  __UpperCAmelCase					:						int = 5_1_2	,  __UpperCAmelCase					:						int = 5_1_2	,  __UpperCAmelCase					:						int = 5_0	,  __UpperCAmelCase					:						float = 7.5	,  __UpperCAmelCase					:						Optional[Union[str, List[str]]] = None	,  __UpperCAmelCase					:						Optional[int] = 1	,  __UpperCAmelCase					:						float = 0.0	,  __UpperCAmelCase					:						Optional[torch.Generator] = None	,  __UpperCAmelCase					:						Optional[torch.FloatTensor] = None	,  __UpperCAmelCase					:						Optional[str] = "pil"	,  __UpperCAmelCase					:						bool = True	,  __UpperCAmelCase					:						Optional[Callable[[int, int, torch.FloatTensor], None]] = None	,  __UpperCAmelCase					:						int = 1	,  **__UpperCAmelCase					:						Union[str, Any]	,  )						->    List[str]:
         """simple docstring"""



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





   @torch.no_grad()
   def       lowercase_				(self					:						int	,  __UpperCAmelCase					:						Union[str, List[str]]	,  __UpperCAmelCase					:						int = 5_1_2	,  __UpperCAmelCase					:						int = 5_1_2	,  __UpperCAmelCase					:						int = 5_0	,  __UpperCAmelCase					:						float = 7.5	,  __UpperCAmelCase					:						Optional[Union[str, List[str]]] = None	,  __UpperCAmelCase					:						Optional[int] = 1	,  __UpperCAmelCase					:						float = 0.0	,  __UpperCAmelCase					:						Optional[torch.Generator] = None	,  __UpperCAmelCase					:						Optional[torch.FloatTensor] = None	,  __UpperCAmelCase					:						Optional[str] = "pil"	,  __UpperCAmelCase					:						bool = True	,  __UpperCAmelCase					:						Optional[Callable[[int, int, torch.FloatTensor], None]] = None	,  __UpperCAmelCase					:						int = 1	,  **__UpperCAmelCase					:						Any	,  )						->    Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  "cuda" if torch.cuda.is_available() else "cpu"
         self.to(__UpperCAmelCase		)

         # 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=__UpperCAmelCase	,  height=__UpperCAmelCase	,  width=__UpperCAmelCase	,  num_inference_steps=__UpperCAmelCase	,  guidance_scale=__UpperCAmelCase	,  negative_prompt=__UpperCAmelCase	,  num_images_per_prompt=__UpperCAmelCase	,  eta=__UpperCAmelCase	,  generator=__UpperCAmelCase	,  latents=__UpperCAmelCase	,  output_type=__UpperCAmelCase	,  return_dict=__UpperCAmelCase	,  callback=__UpperCAmelCase	,  callback_steps=__UpperCAmelCase	,  **__UpperCAmelCase	,  )

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

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

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

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



