






'''simple docstring'''



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

SCREAMING_SNAKE_CASE							=						logging.get_logger(__name__)
@add_end_docstrings(__A					)
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      def __init__(			self      :		List[Any]  ,   **UpperCAmelCase      :		List[Any]		)	->	Dict:


       '''simple docstring'''

       super().__init__(**UpperCAmelCase		)

       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      :		int  ,   UpperCAmelCase      :		Union[str, List[str], "Image", List["Image"]]  ,   **UpperCAmelCase      :		Union[str, Any]		)	->	int:


       '''simple docstring'''

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






      def 					A__   (			self      :		Tuple  ,   **UpperCAmelCase      :		Dict		)	->	Optional[int]:


       '''simple docstring'''

       lowercase       : Optional[int]						={}
       if "candidate_labels" in kwargs:
        lowercase       : List[str]						=kwargs['''candidate_labels''']
       if "hypothesis_template" in kwargs:
        lowercase       : Optional[int]						=kwargs['''hypothesis_template''']

       return preprocess_params, {}, {}






      def 					A__   (			self      :		List[str]  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		List[Any]=None  ,   UpperCAmelCase      :		Any="This is a photo of {}."		)	->	Any:


       '''simple docstring'''

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






      def 					A__   (			self      :		Any  ,   UpperCAmelCase      :		Any		)	->	Dict:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=model_inputs.pop('''candidate_labels'''		)
       lowercase       : Dict						=model_inputs.pop('''text_inputs'''		)
       if isinstance(text_inputs[0]  ,   UpperCAmelCase		):
        lowercase       : List[Any]						=text_inputs[0]
       else:
        # Batching case.
        lowercase       : Optional[Any]						=text_inputs[0][0]

       lowercase       : Any						=self.model(**UpperCAmelCase  ,   **UpperCAmelCase		)

       lowercase       : Optional[int]						={
           '''candidate_labels''': candidate_labels,
           '''logits''': outputs.logits_per_image,
       }
       return model_outputs






      def 					A__   (			self      :		Tuple  ,   UpperCAmelCase      :		Optional[Any]		)	->	List[Any]:


       '''simple docstring'''

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

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









'''simple docstring'''







from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL

from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available
from .timesteps import (
    fastaa_timesteps,
    smartaa_timesteps,
    smartaa_timesteps,
    smartaaa_timesteps,
    smartaaa_timesteps,
    superaa_timesteps,
    superaa_timesteps,
    superaaa_timesteps,
)

@dataclass
class 	_snake_case(			UpperCAmelCase      ):
 __snake_case:							Union[List[PIL.Image.Image], np.ndarray]
 __snake_case:							Optional[List[bool]]
 __snake_case:							Optional[List[bool]]


try:
    if not (is_transformers_available() and is_torch_available()):
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    from ...utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
    from .pipeline_if import IFPipeline
    from .pipeline_if_imgaimg import IFImgaImgPipeline
    from .pipeline_if_imgaimg_superresolution import IFImgaImgSuperResolutionPipeline
    from .pipeline_if_inpainting import IFInpaintingPipeline
    from .pipeline_if_inpainting_superresolution import IFInpaintingSuperResolutionPipeline
    from .pipeline_if_superresolution import IFSuperResolutionPipeline
    from .safety_checker import IFSafetyChecker
    from .watermark import IFWatermarker


