





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

__lowerCamelCase	:					List[Any]			  =					logging.get_logger(__name__)



@add_end_docstrings(__snake_case      )
class  A__       (	__snake_case      ):





      def __init__(			self	,							**A_       ):
       '''simple docstring'''




       super().__init__(**A_       )

       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	,							A_	,							**A_       ):
       '''simple docstring'''




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





      def 	__UpperCamelCase(			self	,							**A_       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[Any]	     =       {}
       if "candidate_labels" in kwargs:
        UpperCamelCase     : Optional[int]	     =       kwargs["candidate_labels"]
       if "hypothesis_template" in kwargs:
        UpperCamelCase     : int	     =       kwargs["hypothesis_template"]

       return preprocess_params, {}, {}





      def 	__UpperCamelCase(			self	,							A_	,							A_=None	,							A_="This is a photo of {}."       ):
       '''simple docstring'''




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





      def 	__UpperCamelCase(			self	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       model_inputs.pop("candidate_labels"       )
       UpperCamelCase     : Optional[Any]	     =       model_inputs.pop("text_inputs"       )
       if isinstance(text_inputs[0]	,							A_       ):
        UpperCamelCase     : Optional[int]	     =       text_inputs[0]
       else:
        # Batching case.
        UpperCamelCase     : List[Any]	     =       text_inputs[0][0]

       UpperCamelCase     : int	     =       self.model(**A_	,							**A_       )

       UpperCamelCase     : str	     =       {
           "candidate_labels": candidate_labels,
           "logits": outputs.logits_per_image,
       }
       return model_outputs





      def 	__UpperCamelCase(			self	,							A_       ):
       '''simple docstring'''




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

       UpperCamelCase     : Tuple	     =       [
           {"score": score, "label": candidate_label}
           for score, candidate_label in sorted(zip(A_	,							A_       )	,							key=lambda A_       : -x[0]       )
       ]
       return result







from typing import Callable, Dict, Optional, Tuple

import torch
from torch import nn
from torch.distributions import (
    AffineTransform,
    Distribution,
    Independent,
    NegativeBinomial,
    Normal,
    StudentT,
    TransformedDistribution,
)



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_=None	,							A_=None	,							A_=0       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       1.0 if scale is None else scale
       UpperCamelCase     : Optional[int]	     =       0.0 if loc is None else loc

       super().__init__(A_	,							[AffineTransform(loc=self.loc	,							scale=self.scale	,							event_dim=A_       )]       )





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return self.base_dist.mean * self.scale + self.loc





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return self.base_dist.variance * self.scale**2





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return self.variance.sqrt()



class  A__       (	nn.Module      ):





      def __init__(			self	,							A_	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       super().__init__(**A_       )
       UpperCamelCase     : Union[str, Any]	     =       args_dim
       UpperCamelCase     : str	     =       nn.ModuleList([nn.Linear(A_	,							A_       ) for dim in args_dim.values()]       )
       UpperCamelCase     : Union[str, Any]	     =       domain_map





      def 	__UpperCamelCase(			self	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : List[Any]	     =       [proj(A_       ) for proj in self.proj]

       return self.domain_map(*A_       )



class  A__       (	nn.Module      ):





      def __init__(			self	,							A_       ):
       '''simple docstring'''




       super().__init__()
       UpperCamelCase     : str	     =       function





      def 	__UpperCamelCase(			self	,							A_	,							*A_       ):
       '''simple docstring'''




       return self.function(A_	,							*A_       )



class  A__       :
      _UpperCAmelCase     :type
      _UpperCAmelCase     :int
      _UpperCAmelCase     :Dict[str, int]





      def __init__(			self	,							A_ = 1       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       dim
       UpperCamelCase     : Union[str, Any]	     =       {k: dim * self.args_dim[k] for k in self.args_dim}





      def 	__UpperCamelCase(			self	,							A_       ):
       '''simple docstring'''




       if self.dim == 1:
        return self.distribution_class(*A_       )
       else:
        return Independent(self.distribution_class(*A_       )	,							1       )





      def 	__UpperCamelCase(			self	,							A_	,							A_ = None	,							A_ = None	,							):
       '''simple docstring'''




       UpperCamelCase     : str	     =       self._base_distribution(A_       )
       if loc is None and scale is None:
        return distr
       else:
        return AffineTransformed(A_	,							loc=A_	,							scale=A_	,							event_dim=self.event_dim       )





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return () if self.dim == 1 else (self.dim,)





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return len(self.event_shape       )





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return 0.0





      def 	__UpperCamelCase(			self	,							A_       ):
       '''simple docstring'''




       return ParameterProjection(
           in_features=A_	,							args_dim=self.args_dim	,							domain_map=LambdaLayer(self.domain_map       )	,							)





      def 	__UpperCamelCase(			self	,							*A_       ):
       '''simple docstring'''




       raise NotImplementedError()





      @staticmethod
      def 	__UpperCamelCase(			A_       ):
       '''simple docstring'''




       return (x + torch.sqrt(torch.square(A_       ) + 4.0       )) / 2.0



class  A__       (	__snake_case      ):
      _UpperCAmelCase     :Dict[str, int]						   =       {"df": 1, "loc": 1, "scale": 1}
      _UpperCAmelCase     :type						   =       StudentT





      @classmethod
      def 	__UpperCamelCase(			cls	,							A_	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[Any]	     =       cls.squareplus(A_       ).clamp_min(torch.finfo(scale.dtype       ).eps       )
       UpperCamelCase     : int	     =       2.0 + cls.squareplus(A_       )
       return df.squeeze(-1       ), loc.squeeze(-1       ), scale.squeeze(-1       )



class  A__       (	__snake_case      ):
      _UpperCAmelCase     :Dict[str, int]						   =       {"loc": 1, "scale": 1}
      _UpperCAmelCase     :type						   =       Normal





      @classmethod
      def 	__UpperCamelCase(			cls	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       cls.squareplus(A_       ).clamp_min(torch.finfo(scale.dtype       ).eps       )
       return loc.squeeze(-1       ), scale.squeeze(-1       )



class  A__       (	__snake_case      ):
      _UpperCAmelCase     :Dict[str, int]						   =       {"total_count": 1, "logits": 1}
      _UpperCAmelCase     :type						   =       NegativeBinomial





      @classmethod
      def 	__UpperCamelCase(			cls	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : List[str]	     =       cls.squareplus(A_       )
       return total_count.squeeze(-1       ), logits.squeeze(-1       )





      def 	__UpperCamelCase(			self	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     ,   UpperCamelCase     : Optional[int]	     =       distr_args
       if self.dim == 1:
        return self.distribution_class(total_count=A_	,							logits=A_       )
       else:
        return Independent(self.distribution_class(total_count=A_	,							logits=A_       )	,							1       )





      def 	__UpperCamelCase(			self	,							A_	,							A_ = None	,							A_ = None       ):
       '''simple docstring'''




       UpperCamelCase     ,   UpperCamelCase     : Any	     =       distr_args

       if scale is not None:
        # See scaling property of Gamma.
        logits += scale.log()

       return self._base_distribution((total_count, logits)       )
