





'''simple docstring'''

from dataclasses import dataclass
from typing import Optional

import torch
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .modeling_utils import ModelMixin







@dataclass
class __a (   _snake_case			):
   __UpperCamelCase   : torch.FloatTensor







class __a (   _snake_case,   _snake_case			):





   @register_to_config
   def __init__(					self				:			Optional[int]				,lowerCamelCase				:			int = 16				,lowerCamelCase				:			int = 88				,lowerCamelCase				:			Optional[int] = None				,lowerCamelCase				:			Optional[int] = None				,lowerCamelCase				:			int = 1				,lowerCamelCase				:			float = 0.0				,lowerCamelCase				:			int = 32				,lowerCamelCase				:			Optional[int] = None				,lowerCamelCase				:			bool = False				,lowerCamelCase				:			Optional[int] = None				,lowerCamelCase				:			str = "geglu"				,lowerCamelCase				:			bool = True				,lowerCamelCase				:			bool = True				,):

      '''simple docstring'''

      super().__init__()
      __SCREAMING_SNAKE_CASE      							=       num_attention_heads
      __SCREAMING_SNAKE_CASE      							=       attention_head_dim
      __SCREAMING_SNAKE_CASE      							=       num_attention_heads * attention_head_dim

      __SCREAMING_SNAKE_CASE      							=       in_channels

      __SCREAMING_SNAKE_CASE      							=       torch.nn.GroupNorm(num_groups=lowerCamelCase				,num_channels=lowerCamelCase				,eps=1E-6				,affine=lowerCamelCase    )
      __SCREAMING_SNAKE_CASE      							=       nn.Linear(lowerCamelCase				,lowerCamelCase    )

      # 3. Define transformers blocks
      __SCREAMING_SNAKE_CASE      							=       nn.ModuleList(
          [
              BasicTransformerBlock(
                  lowerCamelCase				,lowerCamelCase				,lowerCamelCase				,dropout=lowerCamelCase				,cross_attention_dim=lowerCamelCase				,activation_fn=lowerCamelCase				,attention_bias=lowerCamelCase				,double_self_attention=lowerCamelCase				,norm_elementwise_affine=lowerCamelCase				,)
              for d in range(lowerCamelCase    )
          ]    )

      __SCREAMING_SNAKE_CASE      							=       nn.Linear(lowerCamelCase				,lowerCamelCase    )





   def      UpperCAmelCase__     (					self				:			Dict				,lowerCamelCase				:			Tuple				,lowerCamelCase				:			Optional[int]=None				,lowerCamelCase				:			int=None				,lowerCamelCase				:			Dict=None				,lowerCamelCase				:			str=1				,lowerCamelCase				:			int=None				,lowerCamelCase				:			bool = True				,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE      							=       hidden_states.shape
      __SCREAMING_SNAKE_CASE      							=       batch_frames // num_frames

      __SCREAMING_SNAKE_CASE      							=       hidden_states

      __SCREAMING_SNAKE_CASE      							=       hidden_states[None, :].reshape(lowerCamelCase				,lowerCamelCase				,lowerCamelCase				,lowerCamelCase				,lowerCamelCase    )
      __SCREAMING_SNAKE_CASE      							=       hidden_states.permute(0				,2				,1				,3				,4    )

      __SCREAMING_SNAKE_CASE      							=       self.norm(lowerCamelCase    )
      __SCREAMING_SNAKE_CASE      							=       hidden_states.permute(0				,3				,4				,2				,1    ).reshape(batch_size * height * width				,lowerCamelCase				,lowerCamelCase    )

      __SCREAMING_SNAKE_CASE      							=       self.proj_in(lowerCamelCase    )

      # 2. Blocks
      for block in self.transformer_blocks:
         __SCREAMING_SNAKE_CASE      							=       block(
             lowerCamelCase				,encoder_hidden_states=lowerCamelCase				,timestep=lowerCamelCase				,cross_attention_kwargs=lowerCamelCase				,class_labels=lowerCamelCase				,)

      # 3. Output
      __SCREAMING_SNAKE_CASE      							=       self.proj_out(lowerCamelCase    )
      __SCREAMING_SNAKE_CASE      							=       (
          hidden_states[None, None, :]
          .reshape(lowerCamelCase				,lowerCamelCase				,lowerCamelCase				,lowerCamelCase				,lowerCamelCase    )
          .permute(0				,3				,4				,1				,2    )
          .contiguous()
      )
      __SCREAMING_SNAKE_CASE      							=       hidden_states.reshape(lowerCamelCase				,lowerCamelCase				,lowerCamelCase				,lowerCamelCase    )

      __SCREAMING_SNAKE_CASE      							=       hidden_states + residual

      if not return_dict:
         return (output,)

      return TransformerTemporalModelOutput(sample=lowerCamelCase    )












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





