


from copy import deepcopy
from typing import Optional, Union

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available


if is_torch_available():
    import torch

if is_tf_available():
    import tensorflow as tf



class 	__lowerCamelCase			(_a						):
       _lowercase											=     ["""image_processor"""]
       _lowercase											=     """SamImageProcessor"""







       def __init__(			self: Dict,A_: Union[str, Any]					):






            '''simple docstring'''




            super().__init__(A_					)
            __UpperCamelCase =			self.image_processor
            __UpperCamelCase =			-10
            __UpperCamelCase =			self.image_processor.size['longest_edge']







       def __call__(			self: Optional[Any],A_: Optional[int]=None,A_: int=None,A_: str=None,A_: str=None,A_: Optional[Union[str, TensorType]] = None,**A_: Optional[int],):






            '''simple docstring'''




            __UpperCamelCase =			self.image_processor(
                A_,return_tensors=A_,**A_,)

            # pop arguments that are not used in the foward but used nevertheless
            __UpperCamelCase =			encoding_image_processor['original_sizes']

            if hasattr(A_,'numpy'					):  # Checks if Torch or TF tensor
                 __UpperCamelCase =			original_sizes.numpy()

            __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase =			self._check_and_preprocess_points(
                input_points=A_,input_labels=A_,input_boxes=A_,)

            __UpperCamelCase =			self._normalize_and_convert(
                A_,A_,input_points=A_,input_labels=A_,input_boxes=A_,return_tensors=A_,)

            return encoding_image_processor







       def 		snake_case_	(			self: Tuple,A_: Any,A_: str,A_: Dict=None,A_: Dict=None,A_: int=None,A_: List[Any]="pt",):






            '''simple docstring'''




            if input_points is not None:
                 if len(A_					) != len(A_					):
                      __UpperCamelCase =			[
                          self._normalize_coordinates(self.target_size,A_,original_sizes[0]					) for point in input_points
                      ]
                 else:
                      __UpperCamelCase =			[
                          self._normalize_coordinates(self.target_size,A_,A_					)
                          for point, original_size in zip(A_,A_					)
                      ]
                 # check that all arrays have the same shape
                 if not all(point.shape == input_points[0].shape for point in input_points					):
                      if input_labels is not None:
                           __UpperCamelCase,    __UpperCamelCase =			self._pad_points_and_labels(A_,A_					)

                 __UpperCamelCase =			np.array(A_					)

            if input_labels is not None:
                 __UpperCamelCase =			np.array(A_					)

            if input_boxes is not None:
                 if len(A_					) != len(A_					):
                      __UpperCamelCase =			[
                          self._normalize_coordinates(self.target_size,A_,original_sizes[0],is_bounding_box=A_					)
                          for box in input_boxes
                      ]
                 else:
                      __UpperCamelCase =			[
                          self._normalize_coordinates(self.target_size,A_,A_,is_bounding_box=A_					)
                          for box, original_size in zip(A_,A_					)
                      ]
                 __UpperCamelCase =			np.array(A_					)

            if input_boxes is not None:
                 if return_tensors == "pt":
                      __UpperCamelCase =			torch.from_numpy(A_					)
                      # boxes batch size of 1 by default
                      __UpperCamelCase =			input_boxes.unsqueeze(1					) if len(input_boxes.shape					) != 3 else input_boxes
                 elif return_tensors == "tf":
                      __UpperCamelCase =			tf.convert_to_tensor(A_					)
                      # boxes batch size of 1 by default
                      __UpperCamelCase =			tf.expand_dims(A_,1					) if len(input_boxes.shape					) != 3 else input_boxes
                 encoding_image_processor.update({'input_boxes': input_boxes}					)
            if input_points is not None:
                 if return_tensors == "pt":
                      __UpperCamelCase =			torch.from_numpy(A_					)
                      # point batch size of 1 by default
                      __UpperCamelCase =			input_points.unsqueeze(1					) if len(input_points.shape					) != 4 else input_points
                 elif return_tensors == "tf":
                      __UpperCamelCase =			tf.convert_to_tensor(A_					)
                      # point batch size of 1 by default
                      __UpperCamelCase =			tf.expand_dims(A_,1					) if len(input_points.shape					) != 4 else input_points
                 encoding_image_processor.update({'input_points': input_points}					)
            if input_labels is not None:
                 if return_tensors == "pt":
                      __UpperCamelCase =			torch.from_numpy(A_					)
                      # point batch size of 1 by default
                      __UpperCamelCase =			input_labels.unsqueeze(1					) if len(input_labels.shape					) != 3 else input_labels
                 elif return_tensors == "tf":
                      __UpperCamelCase =			tf.convert_to_tensor(A_					)
                      # point batch size of 1 by default
                      __UpperCamelCase =			tf.expand_dims(A_,1					) if len(input_labels.shape					) != 3 else input_labels
                 encoding_image_processor.update({'input_labels': input_labels}					)

            return encoding_image_processor







       def 		snake_case_	(			self: List[str],A_: int,A_: Optional[Any]					):






            '''simple docstring'''




            __UpperCamelCase =			max([point.shape[0] for point in input_points]					)
            __UpperCamelCase =			[]
            for i, point in enumerate(A_					):
                 if point.shape[0] != expected_nb_points:
                      __UpperCamelCase =			np.concatenate(
                          [point, np.zeros((expected_nb_points - point.shape[0], 2)					) + self.point_pad_value],axis=0					)
                      __UpperCamelCase =			np.append(input_labels[i],[self.point_pad_value]					)
                 processed_input_points.append(A_					)
            __UpperCamelCase =			processed_input_points
            return input_points, input_labels







       def 		snake_case_	(			self: Optional[int],A_: int,A_: np.ndarray,A_: Union[str, Any],A_: int=False					):






            '''simple docstring'''




            __UpperCamelCase,    __UpperCamelCase =			original_size
            __UpperCamelCase,    __UpperCamelCase =			self.image_processor._get_preprocess_shape(A_,longest_edge=A_					)
            __UpperCamelCase =			deepcopy(A_					).astype(A_					)

            if is_bounding_box:
                 __UpperCamelCase =			coords.reshape(-1,2,2					)

            __UpperCamelCase =			coords[..., 0] * (new_w / old_w)
            __UpperCamelCase =			coords[..., 1] * (new_h / old_h)

            if is_bounding_box:
                 __UpperCamelCase =			coords.reshape(-1,4					)

            return coords







       def 		snake_case_	(			self: Dict,A_: Optional[Any]=None,A_: List[str]=None,A_: Tuple=None,):






            '''simple docstring'''




            if input_points is not None:
                 if hasattr(A_,'numpy'					):  # Checks for TF or Torch tensor
                      __UpperCamelCase =			input_points.numpy().tolist()

                 if not isinstance(A_,A_					) or not isinstance(input_points[0],A_					):
                      raise ValueError('Input points must be a list of list of floating points.'					)
                 __UpperCamelCase =			[np.array(A_					) for input_point in input_points]
            else:
                 __UpperCamelCase =			None

            if input_labels is not None:
                 if hasattr(A_,'numpy'					):
                      __UpperCamelCase =			input_labels.numpy().tolist()

                 if not isinstance(A_,A_					) or not isinstance(input_labels[0],A_					):
                      raise ValueError('Input labels must be a list of list integers.'					)
                 __UpperCamelCase =			[np.array(A_					) for label in input_labels]
            else:
                 __UpperCamelCase =			None

            if input_boxes is not None:
                 if hasattr(A_,'numpy'					):
                      __UpperCamelCase =			input_boxes.numpy().tolist()

                 if (
                     not isinstance(A_,A_					)
                     or not isinstance(input_boxes[0],A_					)
                     or not isinstance(input_boxes[0][0],A_					)
                 ):
                      raise ValueError('Input boxes must be a list of list of list of floating points.'					)
                 __UpperCamelCase =			[np.array(A_					).astype(np.floataa					) for box in input_boxes]
            else:
                 __UpperCamelCase =			None

            return input_points, input_labels, input_boxes







       @property
       def 		snake_case_	(			self: List[str]					):






            '''simple docstring'''




            __UpperCamelCase =			self.image_processor.model_input_names
            return list(dict.fromkeys(A_					)					)







       def 		snake_case_	(			self: int,*A_: int,**A_: Tuple					):






            '''simple docstring'''




            return self.image_processor.post_process_masks(*A_,**A_					)










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    				=   "CompVis/stable-diffusion-v1-1"
lowercase    				=   "CompVis/stable-diffusion-v1-2"
lowercase    				=   "CompVis/stable-diffusion-v1-3"
lowercase    				=   "CompVis/stable-diffusion-v1-4"




class 					UpperCamelCase_ (     snake_case_							):



	'''simple docstring'''




	def __init__(			self			,     a			,     a			,     a			,     a			,     a			,     a			,     a			,     a = True			,     )			->       int:
								super()._init_()

								snake_case_           =				StableDiffusionPipeline.from_pretrained(a   )
								snake_case_           =				StableDiffusionPipeline.from_pretrained(a   )
								snake_case_           =				StableDiffusionPipeline.from_pretrained(a   )
								snake_case_           =				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   )			->       Dict[str, Any]:
								return {k: getattr(self			,     a   ) for k in self.config.keys() if not k.startswith('_'   )}




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




	def 				_UpperCamelCase     (			self   )			->       List[Any]:
								self.enable_attention_slicing(a   )




	@torch.no_grad()
	def 				_UpperCamelCase     (			self			,     a			,     a = 5_12			,     a = 5_12			,     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			,     )			->       Optional[Any]:
								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 = 5_12			,     a = 5_12			,     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			,     )			->       int:
								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 = 5_12			,     a = 5_12			,     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			,     )			->       Optional[int]:
								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 = 5_12			,     a = 5_12			,     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			,     )			->       Any:
								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 = 5_12			,     a = 5_12			,     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			,     )			->       Optional[Any]:
								snake_case_           =				'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
								snake_case_           =				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
								snake_case_           =				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
								snake_case_           =				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
								snake_case_           =				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]]   )





