



from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
							from PIL import Image

							from ..image_utils import load_image

if is_torch_available():
							from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
							from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
							from ..tf_utils import stable_softmax

__snake_case    :		Dict  =logging.get_logger(__name__)



@add_end_docstrings(lowerCamelCase__)
class 	lowerCamelCase__      (							lowerCamelCase__):




		'''simple docstring'''



		def __init__(self		,**__lowerCamelCase			)					->      Tuple:

						"""simple docstring"""






						super().__init__(**_lowerCAmelCase			)

						requires_backends(self		,'''vision'''			)
						self.check_model_type(
						    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
						    if self.framework == '''tf'''
						    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING			)



		def __call__(self		,__lowerCamelCase		,**__lowerCamelCase			)					->      Union[str, Any]:

						"""simple docstring"""






						return super().__call__(_lowerCAmelCase		,**_lowerCAmelCase			)



		def 		lowerCAmelCase__				(self		,**__lowerCamelCase			)					->      Dict:

						"""simple docstring"""






						lowerCAmelCase__					:    Union[str, Any]												=					{}
						if "candidate_labels" in kwargs:
										lowerCAmelCase__					:    Optional[int]												=					kwargs['''candidate_labels''']
						if "hypothesis_template" in kwargs:
										lowerCAmelCase__					:    Union[str, Any]												=					kwargs['''hypothesis_template''']

						return preprocess_params, {}, {}



		def 		lowerCAmelCase__				(self		,__lowerCamelCase		,__lowerCamelCase=None		,__lowerCamelCase="This is a photo of {}."			)					->      Dict:

						"""simple docstring"""






						lowerCAmelCase__					:    Optional[Any]												=					load_image(_lowerCAmelCase			)
						lowerCAmelCase__					:    Any												=					self.image_processor(images=[image]		,return_tensors=self.framework			)
						lowerCAmelCase__					:    Optional[int]												=					candidate_labels
						lowerCAmelCase__					:    Optional[int]												=					[hypothesis_template.format(_lowerCAmelCase			) for x in candidate_labels]
						lowerCAmelCase__					:    int												=					self.tokenizer(_lowerCAmelCase		,return_tensors=self.framework		,padding=_lowerCAmelCase			)
						lowerCAmelCase__					:    Optional[int]												=					[text_inputs]
						return inputs



		def 		lowerCAmelCase__				(self		,__lowerCamelCase			)					->      List[str]:

						"""simple docstring"""






						lowerCAmelCase__					:    Tuple												=					model_inputs.pop('''candidate_labels'''			)
						lowerCAmelCase__					:    int												=					model_inputs.pop('''text_inputs'''			)
						if isinstance(text_inputs[0]		,_lowerCAmelCase			):
										lowerCAmelCase__					:    Optional[Any]												=					text_inputs[0]
						else:
										# Batching case.
										lowerCAmelCase__					:    Any												=					text_inputs[0][0]

						lowerCAmelCase__					:    str												=					self.model(**_lowerCAmelCase		,**_lowerCAmelCase			)

						lowerCAmelCase__					:    Any												=					{
						    '''candidate_labels''': candidate_labels,
						    '''logits''': outputs.logits_per_image,
						}
						return model_outputs



		def 		lowerCAmelCase__				(self		,__lowerCamelCase			)					->      List[Any]:

						"""simple docstring"""






						lowerCAmelCase__					:    Union[str, Any]												=					model_outputs.pop('''candidate_labels'''			)
						lowerCAmelCase__					:    Union[str, Any]												=					model_outputs['''logits'''][0]
						if self.framework == "pt":
										lowerCAmelCase__					:    Optional[int]												=					logits.softmax(dim=-1			).squeeze(-1			)
										lowerCAmelCase__					:    Any												=					probs.tolist()
										if not isinstance(_lowerCAmelCase		,_lowerCAmelCase			):
														lowerCAmelCase__					:    List[Any]												=					[scores]
						elif self.framework == "tf":
										lowerCAmelCase__					:    Dict												=					stable_softmax(_lowerCAmelCase		,axis=-1			)
										lowerCAmelCase__					:    List[str]												=					probs.numpy().tolist()
						else:
										raise ValueError(f"""Unsupported framework: {self.framework}"""			)

						lowerCAmelCase__					:    List[Any]												=					[
						    {'''score''': score, '''label''': candidate_label}
						    for score, candidate_label in sorted(zip(_lowerCAmelCase		,_lowerCAmelCase			)		,key=lambda __lowerCamelCase			: -x[0]			)
						]
						return result






import random
import unittest

import torch

from diffusers import IFInpaintingSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin



@skip_mps
class 	lowerCamelCase__      (							lowerCamelCase__				,    lowerCamelCase__				,    unittest.TestCase):




		'''simple docstring'''



		snake_case_     =IFInpaintingSuperResolutionPipeline
		snake_case_     =TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""width""", """height"""}
		snake_case_     =TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"""original_image"""})
		snake_case_     =PipelineTesterMixin.required_optional_params - {"""latents"""}



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

						"""simple docstring"""






						return self._get_superresolution_dummy_components()



		def 		lowerCAmelCase__				(self		,__lowerCamelCase		,__lowerCamelCase=0			)					->      Dict:

						"""simple docstring"""






						if str(__lowerCamelCase			).startswith('''mps'''			):
										lowerCAmelCase__					:    Union[str, Any]												=					torch.manual_seed(__lowerCamelCase			)
						else:
										lowerCAmelCase__					:    int												=					torch.Generator(device=__lowerCamelCase			).manual_seed(__lowerCamelCase			)

						lowerCAmelCase__					:    str												=					floats_tensor((1, 3, 16, 16)		,rng=random.Random(__lowerCamelCase			)			).to(__lowerCamelCase			)
						lowerCAmelCase__					:    Optional[Any]												=					floats_tensor((1, 3, 32, 32)		,rng=random.Random(__lowerCamelCase			)			).to(__lowerCamelCase			)
						lowerCAmelCase__					:    Union[str, Any]												=					floats_tensor((1, 3, 32, 32)		,rng=random.Random(__lowerCamelCase			)			).to(__lowerCamelCase			)

						lowerCAmelCase__					:    Dict												=					{
						    '''prompt''': '''A painting of a squirrel eating a burger''',
						    '''image''': image,
						    '''original_image''': original_image,
						    '''mask_image''': mask_image,
						    '''generator''': generator,
						    '''num_inference_steps''': 2,
						    '''output_type''': '''numpy''',
						}

						return inputs



		@unittest.skipIf(
		    torch_device != '''cuda''' or not is_xformers_available()		,reason='''XFormers attention is only available with CUDA and `xformers` installed'''		,)
		def 		lowerCAmelCase__				(self			)					->      int:

						"""simple docstring"""






						self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3			)



		def 		lowerCAmelCase__				(self			)					->      int:

						"""simple docstring"""






						self._test_save_load_optional_components()



		@unittest.skipIf(torch_device != '''cuda'''		,reason='''float16 requires CUDA'''			)
		def 		lowerCAmelCase__				(self			)					->      str:

						"""simple docstring"""






						super().test_save_load_floataa(expected_max_diff=1e-1			)



		def 		lowerCAmelCase__				(self			)					->      Any:

						"""simple docstring"""






						self._test_attention_slicing_forward_pass(expected_max_diff=1e-2			)



		def 		lowerCAmelCase__				(self			)					->      Optional[Any]:

						"""simple docstring"""






						self._test_save_load_local()



		def 		lowerCAmelCase__				(self			)					->      Any:

						"""simple docstring"""






						self._test_inference_batch_single_identical(
						    expected_max_diff=1e-2		,)

