





"""simple docstring"""






import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
		from PIL import Image

		from transformers import AlignProcessor, EfficientNetImageProcessor




@require_vision
class 				__lowercase			(			unittest.TestCase							):







					'''simple docstring'''




					def  _lowerCamelCase		(						self     ):
									__a :						Optional[Any]			       =  tempfile.mkdtemp()

									__a :						List[Any]			       =  [
									    '''[UNK]''',
									    '''[CLS]''',
									    '''[SEP]''',
									    '''[PAD]''',
									    '''[MASK]''',
									    '''want''',
									    '''##want''',
									    '''##ed''',
									    '''wa''',
									    '''un''',
									    '''runn''',
									    '''##ing''',
									    ''',''',
									    '''low''',
									    '''lowest''',
									]
									__a :						Dict			       =  os.path.join(self.tmpdirname	,			VOCAB_FILES_NAMES['''vocab_file''']     )
									with open(self.vocab_file	,			'''w'''	,			encoding='''utf-8'''     ) as vocab_writer:
													vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]     )     )

									__a :						Optional[Any]			       =  {
									    '''do_resize''': True,
									    '''size''': 20,
									    '''do_center_crop''': True,
									    '''crop_size''': 18,
									    '''do_normalize''': True,
									    '''image_mean''': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3],
									    '''image_std''': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1],
									}
									__a :						Union[str, Any]			       =  os.path.join(self.tmpdirname	,			_UpperCAmelCase     )
									with open(self.image_processor_file	,			'''w'''	,			encoding='''utf-8'''     ) as fp:
													json.dump(_UpperCAmelCase	,			_UpperCAmelCase     )







					def  _lowerCamelCase		(						self	,			**_UpperCAmelCase     ):
									return BertTokenizer.from_pretrained(self.tmpdirname	,			**_UpperCAmelCase     )







					def  _lowerCamelCase		(						self	,			**_UpperCAmelCase     ):
									return BertTokenizerFast.from_pretrained(self.tmpdirname	,			**_UpperCAmelCase     )







					def  _lowerCamelCase		(						self	,			**_UpperCAmelCase     ):
									return EfficientNetImageProcessor.from_pretrained(self.tmpdirname	,			**_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									shutil.rmtree(self.tmpdirname     )







					def  _lowerCamelCase		(						self     ):
									__a :						List[str]			       =  [np.random.randint(255	,			size=(3, 30, 400)	,			dtype=np.uinta     )]
									__a :						Union[str, Any]			       =  [Image.fromarray(np.moveaxis(_UpperCAmelCase	,			0	,			-1     )     ) for x in image_inputs]
									return image_inputs







					def  _lowerCamelCase		(						self     ):
									__a :						Optional[Any]			       =  self.get_tokenizer()
									__a :						Dict			       =  self.get_rust_tokenizer()
									__a :						str			       =  self.get_image_processor()

									__a :						Tuple			       =  AlignProcessor(tokenizer=_UpperCAmelCase	,			image_processor=_UpperCAmelCase     )
									processor_slow.save_pretrained(self.tmpdirname     )
									__a :						Any			       =  AlignProcessor.from_pretrained(self.tmpdirname	,			use_fast=_UpperCAmelCase     )

									__a :						str			       =  AlignProcessor(tokenizer=_UpperCAmelCase	,			image_processor=_UpperCAmelCase     )
									processor_fast.save_pretrained(self.tmpdirname     )
									__a :						Any			       =  AlignProcessor.from_pretrained(self.tmpdirname     )

									self.assertEqual(processor_slow.tokenizer.get_vocab()	,			tokenizer_slow.get_vocab()     )
									self.assertEqual(processor_fast.tokenizer.get_vocab()	,			tokenizer_fast.get_vocab()     )
									self.assertEqual(tokenizer_slow.get_vocab()	,			tokenizer_fast.get_vocab()     )
									self.assertIsInstance(processor_slow.tokenizer	,			_UpperCAmelCase     )
									self.assertIsInstance(processor_fast.tokenizer	,			_UpperCAmelCase     )

									self.assertEqual(processor_slow.image_processor.to_json_string()	,			image_processor.to_json_string()     )
									self.assertEqual(processor_fast.image_processor.to_json_string()	,			image_processor.to_json_string()     )
									self.assertIsInstance(processor_slow.image_processor	,			_UpperCAmelCase     )
									self.assertIsInstance(processor_fast.image_processor	,			_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									__a :						List[str]			       =  AlignProcessor(tokenizer=self.get_tokenizer()	,			image_processor=self.get_image_processor()     )
									processor.save_pretrained(self.tmpdirname     )

									__a :						List[Any]			       =  self.get_tokenizer(bos_token='''(BOS)'''	,			eos_token='''(EOS)'''     )
									__a :						Optional[Any]			       =  self.get_image_processor(do_normalize=_UpperCAmelCase	,			padding_value=1.0     )

									__a :						str			       =  AlignProcessor.from_pretrained(
									    self.tmpdirname	,			bos_token='''(BOS)'''	,			eos_token='''(EOS)'''	,			do_normalize=_UpperCAmelCase	,			padding_value=1.0     )

									self.assertEqual(processor.tokenizer.get_vocab()	,			tokenizer_add_kwargs.get_vocab()     )
									self.assertIsInstance(processor.tokenizer	,			_UpperCAmelCase     )

									self.assertEqual(processor.image_processor.to_json_string()	,			image_processor_add_kwargs.to_json_string()     )
									self.assertIsInstance(processor.image_processor	,			_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									__a :						Any			       =  self.get_image_processor()
									__a :						List[str]			       =  self.get_tokenizer()

									__a :						str			       =  AlignProcessor(tokenizer=_UpperCAmelCase	,			image_processor=_UpperCAmelCase     )

									__a :						Optional[Any]			       =  self.prepare_image_inputs()

									__a :						str			       =  image_processor(_UpperCAmelCase	,			return_tensors='''np'''     )
									__a :						Optional[int]			       =  processor(images=_UpperCAmelCase	,			return_tensors='''np'''     )

									for key in input_image_proc.keys():
													self.assertAlmostEqual(input_image_proc[key].sum()	,			input_processor[key].sum()	,			delta=1e-2     )







					def  _lowerCamelCase		(						self     ):
									__a :						List[Any]			       =  self.get_image_processor()
									__a :						Union[str, Any]			       =  self.get_tokenizer()

									__a :						Optional[Any]			       =  AlignProcessor(tokenizer=_UpperCAmelCase	,			image_processor=_UpperCAmelCase     )

									__a :						Tuple			       =  '''lower newer'''

									__a :						int			       =  processor(text=_UpperCAmelCase     )

									__a :						int			       =  tokenizer(_UpperCAmelCase	,			padding='''max_length'''	,			max_length=64     )

									for key in encoded_tok.keys():
													self.assertListEqual(encoded_tok[key]	,			encoded_processor[key]     )







					def  _lowerCamelCase		(						self     ):
									__a :						Optional[Any]			       =  self.get_image_processor()
									__a :						Tuple			       =  self.get_tokenizer()

									__a :						Tuple			       =  AlignProcessor(tokenizer=_UpperCAmelCase	,			image_processor=_UpperCAmelCase     )

									__a :						Optional[int]			       =  '''lower newer'''
									__a :						Union[str, Any]			       =  self.prepare_image_inputs()

									__a :						Optional[int]			       =  processor(text=_UpperCAmelCase	,			images=_UpperCAmelCase     )

									self.assertListEqual(list(inputs.keys()     )	,			['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values''']     )

									# test if it raises when no input is passed
									with pytest.raises(_UpperCAmelCase     ):
													processor()







					def  _lowerCamelCase		(						self     ):
									__a :						str			       =  self.get_image_processor()
									__a :						int			       =  self.get_tokenizer()

									__a :						Optional[Any]			       =  AlignProcessor(tokenizer=_UpperCAmelCase	,			image_processor=_UpperCAmelCase     )

									__a :						Any			       =  [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

									__a :						Dict			       =  processor.batch_decode(_UpperCAmelCase     )
									__a :						Optional[Any]			       =  tokenizer.batch_decode(_UpperCAmelCase     )

									self.assertListEqual(_UpperCAmelCase	,			_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									__a :						List[Any]			       =  self.get_image_processor()
									__a :						Union[str, Any]			       =  self.get_tokenizer()

									__a :						Tuple			       =  AlignProcessor(tokenizer=_UpperCAmelCase	,			image_processor=_UpperCAmelCase     )

									__a :						Dict			       =  '''lower newer'''
									__a :						int			       =  self.prepare_image_inputs()

									__a :						str			       =  processor(text=_UpperCAmelCase	,			images=_UpperCAmelCase     )

									self.assertListEqual(list(inputs.keys()     )	,			processor.model_input_names     )






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


A 			=  logging.get_logger(__name__)

A 			=  {
    '''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			(			_UpperCamelCase							):







					'''simple docstring'''




					__lowerCAmelCase  =  '''detr'''
					__lowerCAmelCase  =  ['''past_key_values''']
					__lowerCAmelCase  =  {
					    '''hidden_size''': '''d_model''',
					    '''num_attention_heads''': '''encoder_attention_heads''',
					}







					def __init__(						self	,			_UpperCAmelCase=True	,			_UpperCAmelCase=None	,			_UpperCAmelCase=3	,			_UpperCAmelCase=100	,			_UpperCAmelCase=6	,			_UpperCAmelCase=2048	,			_UpperCAmelCase=8	,			_UpperCAmelCase=6	,			_UpperCAmelCase=2048	,			_UpperCAmelCase=8	,			_UpperCAmelCase=0.0	,			_UpperCAmelCase=0.0	,			_UpperCAmelCase=True	,			_UpperCAmelCase="relu"	,			_UpperCAmelCase=256	,			_UpperCAmelCase=0.1	,			_UpperCAmelCase=0.0	,			_UpperCAmelCase=0.0	,			_UpperCAmelCase=0.0_2	,			_UpperCAmelCase=1.0	,			_UpperCAmelCase=False	,			_UpperCAmelCase="sine"	,			_UpperCAmelCase="resnet50"	,			_UpperCAmelCase=True	,			_UpperCAmelCase=False	,			_UpperCAmelCase=1	,			_UpperCAmelCase=5	,			_UpperCAmelCase=2	,			_UpperCAmelCase=1	,			_UpperCAmelCase=1	,			_UpperCAmelCase=5	,			_UpperCAmelCase=2	,			_UpperCAmelCase=0.1	,			**_UpperCAmelCase	,			):
									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 :						Any			       =  CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']     )
													elif isinstance(_UpperCAmelCase	,			_UpperCAmelCase     ):
																	__a :						Optional[int]			       =  backbone_config.get('''model_type'''     )
																	__a :						Tuple			       =  CONFIG_MAPPING[backbone_model_type]
																	__a :						Union[str, Any]			       =  config_class.from_dict(_UpperCAmelCase     )
													# set timm attributes to None
													__a       ,						__a       ,						__a :						Union[str, Any]			       =  None, None, None

									__a :						Union[str, Any]			       =  use_timm_backbone
									__a :						Any			       =  backbone_config
									__a :						Tuple			       =  num_channels
									__a :						int			       =  num_queries
									__a :						str			       =  d_model
									__a :						Any			       =  encoder_ffn_dim
									__a :						int			       =  encoder_layers
									__a :						Optional[int]			       =  encoder_attention_heads
									__a :						Any			       =  decoder_ffn_dim
									__a :						str			       =  decoder_layers
									__a :						Union[str, Any]			       =  decoder_attention_heads
									__a :						List[Any]			       =  dropout
									__a :						Union[str, Any]			       =  attention_dropout
									__a :						int			       =  activation_dropout
									__a :						Dict			       =  activation_function
									__a :						str			       =  init_std
									__a :						int			       =  init_xavier_std
									__a :						Optional[Any]			       =  encoder_layerdrop
									__a :						Optional[int]			       =  decoder_layerdrop
									__a :						str			       =  encoder_layers
									__a :						List[str]			       =  auxiliary_loss
									__a :						Optional[Any]			       =  position_embedding_type
									__a :						Any			       =  backbone
									__a :						Tuple			       =  use_pretrained_backbone
									__a :						int			       =  dilation
									# Hungarian matcher
									__a :						str			       =  class_cost
									__a :						Optional[Any]			       =  bbox_cost
									__a :						Any			       =  giou_cost
									# Loss coefficients
									__a :						List[str]			       =  mask_loss_coefficient
									__a :						Dict			       =  dice_loss_coefficient
									__a :						str			       =  bbox_loss_coefficient
									__a :						str			       =  giou_loss_coefficient
									__a :						Any			       =  eos_coefficient
									super().__init__(is_encoder_decoder=_UpperCAmelCase	,			**_UpperCAmelCase     )







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







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







					@classmethod
					def  _lowerCamelCase		(						cls	,			_UpperCAmelCase	,			**_UpperCAmelCase     ):
									return cls(backbone_config=_UpperCAmelCase	,			**_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									__a :						Dict			       =  copy.deepcopy(self.__dict__     )
									if output["backbone_config"] is not None:
													__a :						Tuple			       =  self.backbone_config.to_dict()
									__a :						Dict			       =  self.__class__.model_type
									return output






class 				__lowercase			(			_UpperCamelCase							):







					'''simple docstring'''




					__lowerCAmelCase  =  version.parse('''1.11'''							)







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







					@property
					def  _lowerCamelCase		(						self     ):
									return 1e-5







					@property
					def  _lowerCamelCase		(						self     ):
									return 12