

'''simple docstring'''






import copy
from collections import OrderedDict
from typing import Dict, Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


lowerCAmelCase__											=	logging.get_logger(__name__)

lowerCAmelCase__											=	{
    '''facebook/detr-resnet-50''': '''https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json''',
    # See all DETR models at https://huggingface.co/models?filter=detr
}






class 			lowercase_	(lowerCamelCase__      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  Dict							=			'detr'
  SCREAMING_SNAKE_CASE    :  List[Any]							=			['past_key_values']
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			{
      'hidden_size': 'd_model',
      'num_attention_heads': 'encoder_attention_heads',
  }






  def __init__(      self   :     Tuple					,lowercase__   :     int=True					,lowercase__   :     Union[str, Any]=None					,lowercase__   :     Optional[Any]=3					,lowercase__   :     Optional[Any]=1_0_0					,lowercase__   :     Optional[Any]=6					,lowercase__   :     Optional[int]=2_0_4_8					,lowercase__   :     List[str]=8					,lowercase__   :     Optional[int]=6					,lowercase__   :     Dict=2_0_4_8					,lowercase__   :     List[Any]=8					,lowercase__   :     Optional[int]=0.0					,lowercase__   :     str=0.0					,lowercase__   :     List[str]=True					,lowercase__   :     Union[str, Any]="relu"					,lowercase__   :     List[str]=2_5_6					,lowercase__   :     Optional[int]=0.1					,lowercase__   :     Tuple=0.0					,lowercase__   :     str=0.0					,lowercase__   :     Dict=0.0_2					,lowercase__   :     Tuple=1.0					,lowercase__   :     List[str]=False					,lowercase__   :     Optional[int]="sine"					,lowercase__   :     Any="resnet50"					,lowercase__   :     str=True					,lowercase__   :     Any=False					,lowercase__   :     Tuple=1					,lowercase__   :     Optional[int]=5					,lowercase__   :     Any=2					,lowercase__   :     Union[str, Any]=1					,lowercase__   :     Dict=1					,lowercase__   :     List[str]=5					,lowercase__   :     int=2					,lowercase__   :     Union[str, Any]=0.1					,**lowercase__   :     Tuple					,):
   if backbone_config is not None and use_timm_backbone:
    raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.'''			)

   if not use_timm_backbone:
    if backbone_config is None:
     logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'''			)
     __lowercase							  = CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']			)
    elif isinstance(lowercase__					,lowercase__			):
     __lowercase							  = backbone_config.get('''model_type'''			)
     __lowercase							  = CONFIG_MAPPING[backbone_model_type]
     __lowercase							  = config_class.from_dict(lowercase__			)
    # set timm attributes to None
    __lowercase  ,	__lowercase  ,	__lowercase							  = None, None, None

   __lowercase							  = use_timm_backbone
   __lowercase							  = backbone_config
   __lowercase							  = num_channels
   __lowercase							  = num_queries
   __lowercase							  = d_model
   __lowercase							  = encoder_ffn_dim
   __lowercase							  = encoder_layers
   __lowercase							  = encoder_attention_heads
   __lowercase							  = decoder_ffn_dim
   __lowercase							  = decoder_layers
   __lowercase							  = decoder_attention_heads
   __lowercase							  = dropout
   __lowercase							  = attention_dropout
   __lowercase							  = activation_dropout
   __lowercase							  = activation_function
   __lowercase							  = init_std
   __lowercase							  = init_xavier_std
   __lowercase							  = encoder_layerdrop
   __lowercase							  = decoder_layerdrop
   __lowercase							  = encoder_layers
   __lowercase							  = auxiliary_loss
   __lowercase							  = position_embedding_type
   __lowercase							  = backbone
   __lowercase							  = use_pretrained_backbone
   __lowercase							  = dilation
   # Hungarian matcher
   __lowercase							  = class_cost
   __lowercase							  = bbox_cost
   __lowercase							  = giou_cost
   # Loss coefficients
   __lowercase							  = mask_loss_coefficient
   __lowercase							  = dice_loss_coefficient
   __lowercase							  = bbox_loss_coefficient
   __lowercase							  = giou_loss_coefficient
   __lowercase							  = eos_coefficient
   super().__init__(is_encoder_decoder=lowercase__					,**lowercase__			)






  @property
  def 					SCREAMING_SNAKE_CASE      (      self   :     Tuple			):
   return self.encoder_attention_heads






  @property
  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]			):
   return self.d_model






  @classmethod
  def 					SCREAMING_SNAKE_CASE      (      cls   :     List[str]					,lowercase__   :     PretrainedConfig					,**lowercase__   :     int			):
   return cls(backbone_config=lowercase__					,**lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Any			):
   __lowercase							  = copy.deepcopy(self.__dict__			)
   if output["backbone_config"] is not None:
    __lowercase							  = self.backbone_config.to_dict()
   __lowercase							  = self.__class__.model_type
   return output






class 			lowercase_	(lowerCamelCase__      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  int							=			version.parse('1.11'      )






  @property
  def 					SCREAMING_SNAKE_CASE      (      self   :     List[str]			):
   return OrderedDict(
       [
           ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
           ('''pixel_mask''', {0: '''batch'''}),
       ]			)






  @property
  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[int]			):
   return 1e-5






  @property
  def 					SCREAMING_SNAKE_CASE      (      self   :     Any			):
   return 1_2





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		       =							logging.get_logger(__name__)





@add_end_docstrings(__UpperCamelCase      )
class   __a			(    __UpperCamelCase      ):
 def __init__(   self				, **lowerCAmelCase__ )					->				List[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				, lowerCAmelCase__				, **lowerCAmelCase__ )					->				Optional[Any]:




        '''simple docstring'''
        return super().__call__(lowerCAmelCase__				, **lowerCAmelCase__ )
 def 		SCREAMING_SNAKE_CASE__   (   self				, **lowerCAmelCase__ )					->				Dict:




        '''simple docstring'''
        lowercase__:   int  			=   {}
        if "candidate_labels" in kwargs:
               lowercase__:   Dict  			=   kwargs['candidate_labels']
        if "hypothesis_template" in kwargs:
               lowercase__:   List[Any]  			=   kwargs['hypothesis_template']

        return preprocess_params, {}, {}
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__=None				, lowerCAmelCase__="This is a photo of {}." )					->				int:




        '''simple docstring'''
        lowercase__:   Optional[int]  			=   load_image(lowerCAmelCase__ )
        lowercase__:   Dict  			=   self.image_processor(images=[image]				, return_tensors=self.framework )
        lowercase__:   Tuple  			=   candidate_labels
        lowercase__:   List[str]  			=   [hypothesis_template.format(lowerCAmelCase__ ) for x in candidate_labels]
        lowercase__:   Optional[Any]  			=   self.tokenizer(lowerCAmelCase__				, return_tensors=self.framework				, padding=lowerCAmelCase__ )
        lowercase__:   str  			=   [text_inputs]
        return inputs
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				int:




        '''simple docstring'''
        lowercase__:   str  			=   model_inputs.pop('candidate_labels' )
        lowercase__:   List[str]  			=   model_inputs.pop('text_inputs' )
        if isinstance(text_inputs[0]				, lowerCAmelCase__ ):
               lowercase__:   Any  			=   text_inputs[0]
        else:
               # Batching case.
               lowercase__:   Optional[int]  			=   text_inputs[0][0]

        lowercase__:   Tuple  			=   self.model(**lowerCAmelCase__				, **lowerCAmelCase__ )

        lowercase__:   Any  			=   {
            'candidate_labels': candidate_labels,
            'logits': outputs.logits_per_image,
        }
        return model_outputs
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				Union[str, Any]:




        '''simple docstring'''
        lowercase__:   Tuple  			=   model_outputs.pop('candidate_labels' )
        lowercase__:   Dict  			=   model_outputs['logits'][0]
        if self.framework == "pt":
               lowercase__:   Optional[int]  			=   logits.softmax(dim=-1 ).squeeze(-1 )
               lowercase__:   Dict  			=   probs.tolist()
               if not isinstance(lowerCAmelCase__				, lowerCAmelCase__ ):
                      lowercase__:   Dict  			=   [scores]
        elif self.framework == "tf":
               lowercase__:   Optional[int]  			=   stable_softmax(lowerCAmelCase__				, axis=-1 )
               lowercase__:   Union[str, Any]  			=   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(lowerCAmelCase__				, lowerCAmelCase__ )				, key=lambda lowerCAmelCase__ : -x[0] )
        ]
        return result


