





'''simple docstring'''

import flax.linen as nn
import jax.numpy as jnp

from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD







class __a (   nn.Module			):
   __UpperCamelCase   : int
   __UpperCamelCase   : int
   __UpperCamelCase   : float	      =	0.0
   __UpperCamelCase   : int	      =	1
   __UpperCamelCase   : int	      =	1
   __UpperCamelCase   : bool	      =	True
   __UpperCamelCase   : bool	      =	False
   __UpperCamelCase   : bool	      =	False
   __UpperCamelCase   : bool	      =	False
   __UpperCamelCase   : jnp.dtype	      =	jnp.floataa





   def      UpperCAmelCase__     (					self				:			Union[str, Any]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       []
      __SCREAMING_SNAKE_CASE      							=       []

      for i in range(self.num_layers    ):
         __SCREAMING_SNAKE_CASE      							=       self.in_channels if i == 0 else self.out_channels

         __SCREAMING_SNAKE_CASE      							=       FlaxResnetBlockaD(
             in_channels=lowerCamelCase				,out_channels=self.out_channels				,dropout_prob=self.dropout				,dtype=self.dtype				,)
         resnets.append(lowerCamelCase    )

         __SCREAMING_SNAKE_CASE      							=       FlaxTransformeraDModel(
             in_channels=self.out_channels				,n_heads=self.num_attention_heads				,d_head=self.out_channels // self.num_attention_heads				,depth=1				,use_linear_projection=self.use_linear_projection				,only_cross_attention=self.only_cross_attention				,use_memory_efficient_attention=self.use_memory_efficient_attention				,dtype=self.dtype				,)
         attentions.append(lowerCamelCase    )

      __SCREAMING_SNAKE_CASE      							=       resnets
      __SCREAMING_SNAKE_CASE      							=       attentions

      if self.add_downsample:
         __SCREAMING_SNAKE_CASE      							=       FlaxDownsampleaD(self.out_channels				,dtype=self.dtype    )





   def __call__(					self				:			Any				,lowerCamelCase				:			Dict				,lowerCamelCase				:			List[Any]				,lowerCamelCase				:			Union[str, Any]				,lowerCamelCase				:			Tuple=True    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       ()

      for resnet, attn in zip(self.resnets				,self.attentions    ):
         __SCREAMING_SNAKE_CASE      							=       resnet(lowerCamelCase				,lowerCamelCase				,deterministic=lowerCamelCase    )
         __SCREAMING_SNAKE_CASE      							=       attn(lowerCamelCase				,lowerCamelCase				,deterministic=lowerCamelCase    )
         output_states += (hidden_states,)

      if self.add_downsample:
         __SCREAMING_SNAKE_CASE      							=       self.downsamplers_a(lowerCamelCase    )
         output_states += (hidden_states,)

      return hidden_states, output_states







class __a (   nn.Module			):
   __UpperCamelCase   : int
   __UpperCamelCase   : int
   __UpperCamelCase   : float	      =	0.0
   __UpperCamelCase   : int	      =	1
   __UpperCamelCase   : bool	      =	True
   __UpperCamelCase   : jnp.dtype	      =	jnp.floataa





   def      UpperCAmelCase__     (					self				:			Union[str, Any]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       []

      for i in range(self.num_layers    ):
         __SCREAMING_SNAKE_CASE      							=       self.in_channels if i == 0 else self.out_channels

         __SCREAMING_SNAKE_CASE      							=       FlaxResnetBlockaD(
             in_channels=lowerCamelCase				,out_channels=self.out_channels				,dropout_prob=self.dropout				,dtype=self.dtype				,)
         resnets.append(lowerCamelCase    )
      __SCREAMING_SNAKE_CASE      							=       resnets

      if self.add_downsample:
         __SCREAMING_SNAKE_CASE      							=       FlaxDownsampleaD(self.out_channels				,dtype=self.dtype    )





   def __call__(					self				:			str				,lowerCamelCase				:			Union[str, Any]				,lowerCamelCase				:			Optional[Any]				,lowerCamelCase				:			Dict=True    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       ()

      for resnet in self.resnets:
         __SCREAMING_SNAKE_CASE      							=       resnet(lowerCamelCase				,lowerCamelCase				,deterministic=lowerCamelCase    )
         output_states += (hidden_states,)

      if self.add_downsample:
         __SCREAMING_SNAKE_CASE      							=       self.downsamplers_a(lowerCamelCase    )
         output_states += (hidden_states,)

      return hidden_states, output_states







class __a (   nn.Module			):
   __UpperCamelCase   : int
   __UpperCamelCase   : int
   __UpperCamelCase   : int
   __UpperCamelCase   : float	      =	0.0
   __UpperCamelCase   : int	      =	1
   __UpperCamelCase   : int	      =	1
   __UpperCamelCase   : bool	      =	True
   __UpperCamelCase   : bool	      =	False
   __UpperCamelCase   : bool	      =	False
   __UpperCamelCase   : bool	      =	False
   __UpperCamelCase   : jnp.dtype	      =	jnp.floataa





   def      UpperCAmelCase__     (					self				:			str    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       []
      __SCREAMING_SNAKE_CASE      							=       []

      for i in range(self.num_layers    ):
         __SCREAMING_SNAKE_CASE      							=       self.in_channels if (i == self.num_layers - 1) else self.out_channels
         __SCREAMING_SNAKE_CASE      							=       self.prev_output_channel if i == 0 else self.out_channels

         __SCREAMING_SNAKE_CASE      							=       FlaxResnetBlockaD(
             in_channels=resnet_in_channels + res_skip_channels				,out_channels=self.out_channels				,dropout_prob=self.dropout				,dtype=self.dtype				,)
         resnets.append(lowerCamelCase    )

         __SCREAMING_SNAKE_CASE      							=       FlaxTransformeraDModel(
             in_channels=self.out_channels				,n_heads=self.num_attention_heads				,d_head=self.out_channels // self.num_attention_heads				,depth=1				,use_linear_projection=self.use_linear_projection				,only_cross_attention=self.only_cross_attention				,use_memory_efficient_attention=self.use_memory_efficient_attention				,dtype=self.dtype				,)
         attentions.append(lowerCamelCase    )

      __SCREAMING_SNAKE_CASE      							=       resnets
      __SCREAMING_SNAKE_CASE      							=       attentions

      if self.add_upsample:
         __SCREAMING_SNAKE_CASE      							=       FlaxUpsampleaD(self.out_channels				,dtype=self.dtype    )





   def __call__(					self				:			int				,lowerCamelCase				:			Any				,lowerCamelCase				:			List[Any]				,lowerCamelCase				:			int				,lowerCamelCase				:			Optional[Any]				,lowerCamelCase				:			Union[str, Any]=True    ):

      '''simple docstring'''

      for resnet, attn in zip(self.resnets				,self.attentions    ):
         # pop res hidden states
         __SCREAMING_SNAKE_CASE      							=       res_hidden_states_tuple[-1]
         __SCREAMING_SNAKE_CASE      							=       res_hidden_states_tuple[:-1]
         __SCREAMING_SNAKE_CASE      							=       jnp.concatenate((hidden_states, res_hidden_states)				,axis=-1    )

         __SCREAMING_SNAKE_CASE      							=       resnet(lowerCamelCase				,lowerCamelCase				,deterministic=lowerCamelCase    )
         __SCREAMING_SNAKE_CASE      							=       attn(lowerCamelCase				,lowerCamelCase				,deterministic=lowerCamelCase    )

      if self.add_upsample:
         __SCREAMING_SNAKE_CASE      							=       self.upsamplers_a(lowerCamelCase    )

      return hidden_states







class __a (   nn.Module			):
   __UpperCamelCase   : int
   __UpperCamelCase   : int
   __UpperCamelCase   : int
   __UpperCamelCase   : float	      =	0.0
   __UpperCamelCase   : int	      =	1
   __UpperCamelCase   : bool	      =	True
   __UpperCamelCase   : jnp.dtype	      =	jnp.floataa





   def      UpperCAmelCase__     (					self				:			Tuple    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       []

      for i in range(self.num_layers    ):
         __SCREAMING_SNAKE_CASE      							=       self.in_channels if (i == self.num_layers - 1) else self.out_channels
         __SCREAMING_SNAKE_CASE      							=       self.prev_output_channel if i == 0 else self.out_channels

         __SCREAMING_SNAKE_CASE      							=       FlaxResnetBlockaD(
             in_channels=resnet_in_channels + res_skip_channels				,out_channels=self.out_channels				,dropout_prob=self.dropout				,dtype=self.dtype				,)
         resnets.append(lowerCamelCase    )

      __SCREAMING_SNAKE_CASE      							=       resnets

      if self.add_upsample:
         __SCREAMING_SNAKE_CASE      							=       FlaxUpsampleaD(self.out_channels				,dtype=self.dtype    )





   def __call__(					self				:			Dict				,lowerCamelCase				:			Tuple				,lowerCamelCase				:			Optional[Any]				,lowerCamelCase				:			Optional[Any]				,lowerCamelCase				:			Tuple=True    ):

      '''simple docstring'''

      for resnet in self.resnets:
         # pop res hidden states
         __SCREAMING_SNAKE_CASE      							=       res_hidden_states_tuple[-1]
         __SCREAMING_SNAKE_CASE      							=       res_hidden_states_tuple[:-1]
         __SCREAMING_SNAKE_CASE      							=       jnp.concatenate((hidden_states, res_hidden_states)				,axis=-1    )

         __SCREAMING_SNAKE_CASE      							=       resnet(lowerCamelCase				,lowerCamelCase				,deterministic=lowerCamelCase    )

      if self.add_upsample:
         __SCREAMING_SNAKE_CASE      							=       self.upsamplers_a(lowerCamelCase    )

      return hidden_states







class __a (   nn.Module			):
   __UpperCamelCase   : int
   __UpperCamelCase   : float	      =	0.0
   __UpperCamelCase   : int	      =	1
   __UpperCamelCase   : int	      =	1
   __UpperCamelCase   : bool	      =	False
   __UpperCamelCase   : bool	      =	False
   __UpperCamelCase   : jnp.dtype	      =	jnp.floataa





   def      UpperCAmelCase__     (					self				:			List[str]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       [
          FlaxResnetBlockaD(
              in_channels=self.in_channels				,out_channels=self.in_channels				,dropout_prob=self.dropout				,dtype=self.dtype				,)
      ]

      __SCREAMING_SNAKE_CASE      							=       []

      for _ in range(self.num_layers    ):
         __SCREAMING_SNAKE_CASE      							=       FlaxTransformeraDModel(
             in_channels=self.in_channels				,n_heads=self.num_attention_heads				,d_head=self.in_channels // self.num_attention_heads				,depth=1				,use_linear_projection=self.use_linear_projection				,use_memory_efficient_attention=self.use_memory_efficient_attention				,dtype=self.dtype				,)
         attentions.append(lowerCamelCase    )

         __SCREAMING_SNAKE_CASE      							=       FlaxResnetBlockaD(
             in_channels=self.in_channels				,out_channels=self.in_channels				,dropout_prob=self.dropout				,dtype=self.dtype				,)
         resnets.append(lowerCamelCase    )

      __SCREAMING_SNAKE_CASE      							=       resnets
      __SCREAMING_SNAKE_CASE      							=       attentions





   def __call__(					self				:			List[str]				,lowerCamelCase				:			List[Any]				,lowerCamelCase				:			Any				,lowerCamelCase				:			Tuple				,lowerCamelCase				:			Any=True    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.resnets[0](lowerCamelCase				,lowerCamelCase    )
      for attn, resnet in zip(self.attentions				,self.resnets[1:]    ):
         __SCREAMING_SNAKE_CASE      							=       attn(lowerCamelCase				,lowerCamelCase				,deterministic=lowerCamelCase    )
         __SCREAMING_SNAKE_CASE      							=       resnet(lowerCamelCase				,lowerCamelCase				,deterministic=lowerCamelCase    )

      return hidden_states












'''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

a        =						logging.get_logger(__name__)







@add_end_docstrings(_snake_case			)
class __a (   _snake_case			):





   def __init__(					self				:			Union[str, Any]				,**lowerCamelCase				:			str    ):

      '''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				:			Dict				,lowerCamelCase				:			Union[str, List[str], "Image", List["Image"]]				,**lowerCamelCase				:			Optional[Any]    ):

      '''simple docstring'''

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





   def      UpperCAmelCase__     (					self				:			Optional[Any]				,**lowerCamelCase				:			Optional[int]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       {}
      if "candidate_labels" in kwargs:
         __SCREAMING_SNAKE_CASE      							=       kwargs["""candidate_labels"""]
      if "hypothesis_template" in kwargs:
         __SCREAMING_SNAKE_CASE      							=       kwargs["""hypothesis_template"""]

      return preprocess_params, {}, {}





   def      UpperCAmelCase__     (					self				:			List[Any]				,lowerCamelCase				:			List[Any]				,lowerCamelCase				:			Union[str, Any]=None				,lowerCamelCase				:			Union[str, Any]="This is a photo of {}."    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       load_image(lowerCamelCase    )
      __SCREAMING_SNAKE_CASE      							=       self.image_processor(images=[image]				,return_tensors=self.framework    )
      __SCREAMING_SNAKE_CASE      							=       candidate_labels
      __SCREAMING_SNAKE_CASE      							=       [hypothesis_template.format(lowerCamelCase    ) for x in candidate_labels]
      __SCREAMING_SNAKE_CASE      							=       self.tokenizer(lowerCamelCase				,return_tensors=self.framework				,padding=lowerCamelCase    )
      __SCREAMING_SNAKE_CASE      							=       [text_inputs]
      return inputs





   def      UpperCAmelCase__     (					self				:			Tuple				,lowerCamelCase				:			str    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       model_inputs.pop("""candidate_labels"""    )
      __SCREAMING_SNAKE_CASE      							=       model_inputs.pop("""text_inputs"""    )
      if isinstance(text_inputs[0]				,lowerCamelCase    ):
         __SCREAMING_SNAKE_CASE      							=       text_inputs[0]
      else:
         # Batching case.
         __SCREAMING_SNAKE_CASE      							=       text_inputs[0][0]

      __SCREAMING_SNAKE_CASE      							=       self.model(**lowerCamelCase				,**lowerCamelCase    )

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





   def      UpperCAmelCase__     (					self				:			Dict				,lowerCamelCase				:			Tuple    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       model_outputs.pop("""candidate_labels"""    )
      __SCREAMING_SNAKE_CASE      							=       model_outputs["""logits"""][0]
      if self.framework == "pt":
         __SCREAMING_SNAKE_CASE      							=       logits.softmax(dim=-1    ).squeeze(-1    )
         __SCREAMING_SNAKE_CASE      							=       probs.tolist()
         if not isinstance(lowerCamelCase				,lowerCamelCase    ):
            __SCREAMING_SNAKE_CASE      							=       [scores]
      elif self.framework == "tf":
         __SCREAMING_SNAKE_CASE      							=       stable_softmax(lowerCamelCase				,axis=-1    )
         __SCREAMING_SNAKE_CASE      							=       probs.numpy().tolist()
      else:
         raise ValueError(f"""Unsupported framework: {self.framework}"""    )

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





