





"""simple docstring"""





from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
  import torch


__A											=						logging.get_logger(__name__)






class    _lowerCAmelCase  (	a			):
       """simple docstring"""




       __magic_name__	:int						    =   ["""pixel_values"""]






       def __init__(       self       ,					__UpperCAmelCase = True       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = PILImageResampling.BILINEAR       ,					__UpperCAmelCase = True       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = True       ,					__UpperCAmelCase = 1 / 2_5_5       ,					__UpperCAmelCase = True       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					**__UpperCAmelCase       ,					):



         '''simple docstring'''

         super().__init__(**__UpperCAmelCase )
         lowerCAmelCase__     :int											=				size if size is not None else {'shortest_edge': 2_5_6}
         lowerCAmelCase__     :Optional[int]											=				get_size_dict(__UpperCAmelCase       ,					default_to_square=__UpperCAmelCase )
         lowerCAmelCase__     :str											=				crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
         lowerCAmelCase__     :Optional[int]											=				get_size_dict(__UpperCAmelCase       ,					param_name='crop_size' )
         lowerCAmelCase__     :Optional[Any]											=				do_resize
         lowerCAmelCase__     :Dict											=				size
         lowerCAmelCase__     :Tuple											=				resample
         lowerCAmelCase__     :Any											=				do_center_crop
         lowerCAmelCase__     :Tuple											=				crop_size
         lowerCAmelCase__     :List[Any]											=				do_rescale
         lowerCAmelCase__     :Any											=				rescale_factor
         lowerCAmelCase__     :Tuple											=				do_normalize
         lowerCAmelCase__     :Optional[Any]											=				image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
         lowerCAmelCase__     :List[str]											=				image_std if image_std is not None else IMAGENET_STANDARD_STD






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase = PILImageResampling.BICUBIC       ,					__UpperCAmelCase = None       ,					**__UpperCAmelCase       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :Optional[Any]											=				get_size_dict(__UpperCAmelCase       ,					default_to_square=__UpperCAmelCase )
         if "shortest_edge" not in size:
           raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" )
         lowerCAmelCase__     :Any											=				get_resize_output_image_size(__UpperCAmelCase       ,					size=size['shortest_edge']       ,					default_to_square=__UpperCAmelCase )
         return resize(__UpperCAmelCase       ,					size=__UpperCAmelCase       ,					resample=__UpperCAmelCase       ,					data_format=__UpperCAmelCase       ,					**__UpperCAmelCase )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase = None       ,					**__UpperCAmelCase       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :Dict											=				get_size_dict(__UpperCAmelCase )
         if "height" not in size or "width" not in size:
           raise ValueError(F"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}" )
         return center_crop(__UpperCAmelCase       ,					size=(size['height'], size['width'])       ,					data_format=__UpperCAmelCase       ,					**__UpperCAmelCase )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase = None       ,					**__UpperCAmelCase ):



         '''simple docstring'''

         return rescale(__UpperCAmelCase       ,					scale=__UpperCAmelCase       ,					data_format=__UpperCAmelCase       ,					**__UpperCAmelCase )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase = None       ,					**__UpperCAmelCase       ,					):



         '''simple docstring'''

         return normalize(__UpperCAmelCase       ,					mean=__UpperCAmelCase       ,					std=__UpperCAmelCase       ,					data_format=__UpperCAmelCase       ,					**__UpperCAmelCase )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = ChannelDimension.FIRST       ,					**__UpperCAmelCase       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :Optional[int]											=				do_resize if do_resize is not None else self.do_resize
         lowerCAmelCase__     :int											=				size if size is not None else self.size
         lowerCAmelCase__     :Optional[Any]											=				get_size_dict(__UpperCAmelCase       ,					default_to_square=__UpperCAmelCase )
         lowerCAmelCase__     :List[Any]											=				resample if resample is not None else self.resample
         lowerCAmelCase__     :List[str]											=				do_center_crop if do_center_crop is not None else self.do_center_crop
         lowerCAmelCase__     :List[str]											=				crop_size if crop_size is not None else self.crop_size
         lowerCAmelCase__     :Union[str, Any]											=				get_size_dict(__UpperCAmelCase       ,					param_name='crop_size' )
         lowerCAmelCase__     :List[str]											=				do_rescale if do_rescale is not None else self.do_rescale
         lowerCAmelCase__     :List[str]											=				rescale_factor if rescale_factor is not None else self.rescale_factor
         lowerCAmelCase__     :List[Any]											=				do_normalize if do_normalize is not None else self.do_normalize
         lowerCAmelCase__     :Union[str, Any]											=				image_mean if image_mean is not None else self.image_mean
         lowerCAmelCase__     :Optional[int]											=				image_std if image_std is not None else self.image_std

         lowerCAmelCase__     :List[str]											=				make_list_of_images(__UpperCAmelCase )

         if not valid_images(__UpperCAmelCase ):
           raise ValueError(
               'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
               'torch.Tensor, tf.Tensor or jax.ndarray.' )

         if do_resize and size is None:
           raise ValueError('Size must be specified if do_resize is True.' )

         if do_center_crop and crop_size is None:
           raise ValueError('Crop size must be specified if do_center_crop is True.' )

         if do_rescale and rescale_factor is None:
           raise ValueError('Rescale factor must be specified if do_rescale is True.' )

         if do_normalize and (image_mean is None or image_std is None):
           raise ValueError('Image mean and std must be specified if do_normalize is True.' )

         # All transformations expect numpy arrays.
         lowerCAmelCase__     :Optional[int]											=				[to_numpy_array(__UpperCAmelCase ) for image in images]

         if do_resize:
           lowerCAmelCase__     :Tuple											=				[self.resize(image=__UpperCAmelCase       ,					size=__UpperCAmelCase       ,					resample=__UpperCAmelCase ) for image in images]

         if do_center_crop:
           lowerCAmelCase__     :Union[str, Any]											=				[self.center_crop(image=__UpperCAmelCase       ,					size=__UpperCAmelCase ) for image in images]

         if do_rescale:
           lowerCAmelCase__     :Union[str, Any]											=				[self.rescale(image=__UpperCAmelCase       ,					scale=__UpperCAmelCase ) for image in images]

         if do_normalize:
           lowerCAmelCase__     :List[str]											=				[self.normalize(image=__UpperCAmelCase       ,					mean=__UpperCAmelCase       ,					std=__UpperCAmelCase ) for image in images]

         lowerCAmelCase__     :Dict											=				[to_channel_dimension_format(__UpperCAmelCase       ,					__UpperCAmelCase ) for image in images]

         lowerCAmelCase__     :List[str]											=				{'pixel_values': images}
         return BatchFeature(data=__UpperCAmelCase       ,					tensor_type=__UpperCAmelCase )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase = None ):



         '''simple docstring'''

         lowerCAmelCase__     :int											=				outputs.logits

         # Resize logits and compute semantic segmentation maps
         if target_sizes is not None:
           if len(__UpperCAmelCase ) != len(__UpperCAmelCase ):
             raise ValueError(
                 'Make sure that you pass in as many target sizes as the batch dimension of the logits' )

           if is_torch_tensor(__UpperCAmelCase ):
             lowerCAmelCase__     :Optional[Any]											=				target_sizes.numpy()

           lowerCAmelCase__     :List[str]											=				[]

           for idx in range(len(__UpperCAmelCase ) ):
             lowerCAmelCase__     :Optional[Any]											=				torch.nn.functional.interpolate(
                 logits[idx].unsqueeze(dim=0 )       ,					size=target_sizes[idx]       ,					mode='bilinear'       ,					align_corners=__UpperCAmelCase )
             lowerCAmelCase__     :Tuple											=				resized_logits[0].argmax(dim=0 )
             semantic_segmentation.append(__UpperCAmelCase )
         else:
           lowerCAmelCase__     :List[str]											=				logits.argmax(dim=1 )
           lowerCAmelCase__     :Tuple											=				[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )]

         return semantic_segmentation







import copy
from collections import OrderedDict
from typing import Mapping

from packaging import version

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


a__: Optional[Any]							   =						logging.get_logger(__name__)

a__: Any							   =						{
    'microsoft/conditional-detr-resnet-50': (
        'https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json'
    ),
}




class        SCREAMING_SNAKE_CASE__					(		UpperCamelCase__ ):
 __SCREAMING_SNAKE_CASE							=      '''conditional_detr'''
 __SCREAMING_SNAKE_CASE							=      ['''past_key_values''']
 __SCREAMING_SNAKE_CASE							=      {
     '''hidden_size''': '''d_model''',
     '''num_attention_heads''': '''encoder_attention_heads''',
 }



 def __init__(				self,__lowerCamelCase=True,__lowerCamelCase=None,__lowerCamelCase=3,__lowerCamelCase=300,__lowerCamelCase=6,__lowerCamelCase=2048,__lowerCamelCase=8,__lowerCamelCase=6,__lowerCamelCase=2048,__lowerCamelCase=8,__lowerCamelCase=0.0,__lowerCamelCase=0.0,__lowerCamelCase=True,__lowerCamelCase="relu",__lowerCamelCase=256,__lowerCamelCase=0.1,__lowerCamelCase=0.0,__lowerCamelCase=0.0,__lowerCamelCase=0.02,__lowerCamelCase=1.0,__lowerCamelCase=False,__lowerCamelCase="sine",__lowerCamelCase="resnet50",__lowerCamelCase=True,__lowerCamelCase=False,__lowerCamelCase=2,__lowerCamelCase=5,__lowerCamelCase=2,__lowerCamelCase=1,__lowerCamelCase=1,__lowerCamelCase=2,__lowerCamelCase=5,__lowerCamelCase=2,__lowerCamelCase=0.25,**__lowerCamelCase,):
        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.'''					)
                      A__		   =		CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']					)
               elif isinstance(__lowerCamelCase,__lowerCamelCase					):
                      A__		   =		backbone_config.get('''model_type'''					)
                      A__		   =		CONFIG_MAPPING[backbone_model_type]
                      A__		   =		config_class.from_dict(__lowerCamelCase					)

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



 @property
 def 							UpperCamelCase     (				self					):
        return self.encoder_attention_heads



 @property
 def 							UpperCamelCase     (				self					):
        return self.d_model




 def 							UpperCamelCase     (				self					):
        A__		   =		copy.deepcopy(self.__dict__					)
        if self.backbone_config is not None:
               A__		   =		self.backbone_config.to_dict()
        A__		   =		self.__class__.model_type
        return output




class        SCREAMING_SNAKE_CASE__					(		UpperCamelCase__ ):
 __SCREAMING_SNAKE_CASE							=      version.parse('''1.11''' )



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



 @property
 def 							UpperCamelCase     (				self					):
        return 1E-5




 @property
 def 							UpperCamelCase     (				self					):
        return 12





