




from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
	import tensorflow as tf

	from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor







class   A:



	'''simple docstring'''


	def __init__(    self :  str						,							A_ :  Optional[int]						,							A_ :  str=3						,							A_ :  Optional[int]=32						,							A_ :  Optional[Any]=3						,							A_ :  Optional[int]=10						,							A_ :  List[Any]=[10, 20, 30, 40]						,							A_ :  Dict=[1, 1, 2, 1]						,							A_ :  Tuple=True						,							A_ :  Union[str, Any]=True						,							A_ :  Dict="relu"						,							A_ :  Any=3						,							A_ :  str=None						,							)       ->     int:

							"""simple docstring"""






							lowerCamelCase_							=   parent
							lowerCamelCase_							=   batch_size
							lowerCamelCase_							=   image_size
							lowerCamelCase_							=   num_channels
							lowerCamelCase_							=   embeddings_size
							lowerCamelCase_							=   hidden_sizes
							lowerCamelCase_							=   depths
							lowerCamelCase_							=   is_training
							lowerCamelCase_							=   use_labels
							lowerCamelCase_							=   hidden_act
							lowerCamelCase_							=   num_labels
							lowerCamelCase_							=   scope
							lowerCamelCase_							=   len(__a  )

	def     a__			(    self :  int  )       ->     Optional[int]:

							"""simple docstring"""






							lowerCamelCase_							=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

							lowerCamelCase_							=   None
							if self.use_labels:
													lowerCamelCase_							=   ids_tensor([self.batch_size]						,							self.num_labels  )

							lowerCamelCase_							=   self.get_config()
							return config, pixel_values, labels

	def     a__			(    self :  Optional[Any]  )       ->     Dict:

							"""simple docstring"""






							return RegNetConfig(
							    num_channels=self.num_channels						,							embeddings_size=self.embeddings_size						,							hidden_sizes=self.hidden_sizes						,							depths=self.depths						,							hidden_act=self.hidden_act						,							num_labels=self.num_labels						,							)

	def     a__			(    self :  Optional[Any]						,							A_ :  Any						,							A_ :  Union[str, Any]						,							A_ :  Union[str, Any]  )       ->     str:

							"""simple docstring"""






							lowerCamelCase_							=   TFRegNetModel(config=__a  )
							lowerCamelCase_							=   model(__a						,							training=__a  )
							# expected last hidden states: B, C, H // 32, W // 32
							self.parent.assertEqual(
							    result.last_hidden_state.shape						,							(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						,							)

	def     a__			(    self :  List[str]						,							A_ :  Dict						,							A_ :  Union[str, Any]						,							A_ :  Optional[Any]  )       ->     Tuple:

							"""simple docstring"""






							lowerCamelCase_							=   self.num_labels
							lowerCamelCase_							=   TFRegNetForImageClassification(__a  )
							lowerCamelCase_							=   model(__a						,							labels=__a						,							training=__a  )
							self.parent.assertEqual(result.logits.shape						,							(self.batch_size, self.num_labels)  )





	def     a__			(    self :  int  )       ->     List[Any]:

							"""simple docstring"""






							lowerCamelCase_							=   self.prepare_config_and_inputs()
							lowerCamelCase_							=   config_and_inputs
							lowerCamelCase_							=   {'pixel_values': pixel_values}
							return config, inputs_dict







@require_tf
class   A(						SCREAMING_SNAKE_CASE_							,				SCREAMING_SNAKE_CASE_							,				unittest.TestCase       ):



	'''simple docstring'''


	UpperCamelCase						       =						(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
	UpperCamelCase						       =						(
	    {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	UpperCamelCase						       =						False
	UpperCamelCase						       =						False
	UpperCamelCase						       =						False
	UpperCamelCase						       =						False
	UpperCamelCase						       =						False

	def     a__			(    self :  List[str]  )       ->     Tuple:

							"""simple docstring"""






							lowerCamelCase_							=   TFRegNetModelTester(self  )
							lowerCamelCase_							=   ConfigTester(self						,							config_class=__a						,							has_text_modality=__a  )

	def     a__			(    self :  Optional[int]  )       ->     Tuple:

							"""simple docstring"""






							return

	@unittest.skip(reason='RegNet does not use inputs_embeds'  )
	def     a__			(    self :  List[Any]  )       ->     List[str]:

							"""simple docstring"""






							pass

	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('GPU'  )  ) == 0						,							reason='TF does not support backprop for grouped convolutions on CPU.'						,							)
	@slow
	def     a__			(    self :  List[str]  )       ->     Any:

							"""simple docstring"""






							super().test_keras_fit()

	@unittest.skip(reason='RegNet does not support input and output embeddings'  )
	def     a__			(    self :  str  )       ->     str:

							"""simple docstring"""






							pass

	def     a__			(    self :  List[str]  )       ->     List[str]:

							"""simple docstring"""






							lowerCamelCase_							=   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													lowerCamelCase_							=   model_class(__a  )
													lowerCamelCase_							=   inspect.signature(model.call  )
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													lowerCamelCase_							=   [*signature.parameters.keys()]

													lowerCamelCase_							=   ['pixel_values']
													self.assertListEqual(arg_names[:1]						,							__a  )

	def     a__			(    self :  List[Any]  )       ->     Optional[Any]:

							"""simple docstring"""






							lowerCamelCase_							=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__a  )

	def     a__			(    self :  Optional[Any]  )       ->     Dict:

							"""simple docstring"""






							def check_hidden_states_output(A_ :  List[str]						,							A_ :  List[Any]						,							A_ :  Optional[Any]  ):
													lowerCamelCase_							=   model_class(__a  )
													lowerCamelCase_							=   model(**self._prepare_for_class(__a						,							__a  )						,							training=__a  )

													lowerCamelCase_							=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													lowerCamelCase_							=   self.model_tester.num_stages
													self.assertEqual(len(__a  )						,							expected_num_stages + 1  )

													# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
													self.assertListEqual(
													    list(hidden_states[0].shape[-2:]  )						,							[self.model_tester.image_size // 2, self.model_tester.image_size // 2]						,							)

							lowerCamelCase_							=   self.model_tester.prepare_config_and_inputs_for_common()
							lowerCamelCase_							=   ['basic', 'bottleneck']
							for model_class in self.all_model_classes:
													for layer_type in layers_type:
																			lowerCamelCase_							=   layer_type
																			lowerCamelCase_							=   True
																			check_hidden_states_output(__a						,							__a						,							__a  )

																			# check that output_hidden_states also work using config
																			del inputs_dict["output_hidden_states"]
																			lowerCamelCase_							=   True

																			check_hidden_states_output(__a						,							__a						,							__a  )

	def     a__			(    self :  Tuple  )       ->     List[str]:

							"""simple docstring"""






							lowerCamelCase_							=   self.model_tester.prepare_config_and_inputs_for_common()

							def check_equivalence(A_ :  Optional[int]						,							A_ :  Tuple						,							A_ :  Union[str, Any]						,							A_ :  List[Any]={}  ):
													lowerCamelCase_							=   model(__a						,							return_dict=__a						,							**__a  )
													lowerCamelCase_							=   model(__a						,							return_dict=__a						,							**__a  ).to_tuple()

													def recursive_check(A_ :  Tuple						,							A_ :  Optional[int]  ):
																			if isinstance(__a						,							(List, Tuple)  ):
																									for tuple_iterable_value, dict_iterable_value in zip(__a						,							__a  ):
																															recursive_check(__a						,							__a  )
																			elif tuple_object is None:
																									return
																			else:
																									self.assertTrue(
																									    all(tf.equal(__a						,							__a  )  )						,							msg=(
																									        'Tuple and dict output are not equal. Difference:'
																									        f""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object  )  )}"""
																									    )						,							)

																			recursive_check(__a						,							__a  )

							for model_class in self.all_model_classes:
													lowerCamelCase_							=   model_class(__a  )

													lowerCamelCase_							=   self._prepare_for_class(__a						,							__a  )
													lowerCamelCase_							=   self._prepare_for_class(__a						,							__a  )
													check_equivalence(__a						,							__a						,							__a  )

													lowerCamelCase_							=   self._prepare_for_class(__a						,							__a						,							return_labels=__a  )
													lowerCamelCase_							=   self._prepare_for_class(__a						,							__a						,							return_labels=__a  )
													check_equivalence(__a						,							__a						,							__a  )

													lowerCamelCase_							=   self._prepare_for_class(__a						,							__a  )
													lowerCamelCase_							=   self._prepare_for_class(__a						,							__a  )
													check_equivalence(__a						,							__a						,							__a						,							{'output_hidden_states': True}  )

													lowerCamelCase_							=   self._prepare_for_class(__a						,							__a						,							return_labels=__a  )
													lowerCamelCase_							=   self._prepare_for_class(__a						,							__a						,							return_labels=__a  )
													check_equivalence(__a						,							__a						,							__a						,							{'output_hidden_states': True}  )

	def     a__			(    self :  str  )       ->     Optional[int]:

							"""simple docstring"""






							lowerCamelCase_							=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__a  )





	@slow
	def     a__			(    self :  Union[str, Any]  )       ->     int:

							"""simple docstring"""






							for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowerCamelCase_							=   TFRegNetModel.from_pretrained(__a  )
													self.assertIsNotNone(__a  )

def       _SCREAMING_SNAKE_CASE      (							):


						'''simple docstring'''



						lowerCamelCase_							=   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
						return image







@require_tf
@require_vision
class   A(						unittest.TestCase       ):



	'''simple docstring'''


	@cached_property
	def     a__			(    self :  List[Any]  )       ->     str:

							"""simple docstring"""






							return (
							    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )
							    if is_vision_available()
							    else None
							)





	@slow
	def     a__			(    self :  Optional[Any]  )       ->     Optional[int]:

							"""simple docstring"""






							lowerCamelCase_							=   TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

							lowerCamelCase_							=   self.default_image_processor
							lowerCamelCase_							=   prepare_img()
							lowerCamelCase_							=   image_processor(images=__a						,							return_tensors='tf'  )

							# forward pass
							lowerCamelCase_							=   model(**__a						,							training=__a  )

							# verify the logits
							lowerCamelCase_							=   tf.TensorShape((1, 1000)  )
							self.assertEqual(outputs.logits.shape						,							__a  )

							lowerCamelCase_							=   tf.constant([-0.4180, -1.5051, -3.4836]  )

							tf.debugging.assert_near(outputs.logits[0, :3]						,							__a						,							atol=1E-4  )









import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available







class   A(						UpperCamelCase       ):



 '''simple docstring'''


 UpperCamelCase						       =						['''image_processor''', '''tokenizer''']
 UpperCamelCase						       =						'''OwlViTImageProcessor'''
 UpperCamelCase						       =						('''CLIPTokenizer''', '''CLIPTokenizerFast''')

 def __init__(    self :  Optional[Any]						,							A_ :  Tuple=None						,							A_ :  Tuple=None						,							**A_ :  List[str]  )       ->     Any:

       """simple docstring"""






       lowerCamelCase_							=   None
       if "feature_extractor" in kwargs:
             warnings.warn(
                 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
                 ' instead.'						,							A_						,							)
             lowerCamelCase_							=   kwargs.pop('feature_extractor'  )

       lowerCamelCase_							=   image_processor if image_processor is not None else feature_extractor
       if image_processor is None:
             raise ValueError('You need to specify an `image_processor`.'  )
       if tokenizer is None:
             raise ValueError('You need to specify a `tokenizer`.'  )

       super().__init__(A_						,							A_  )

 def __call__(    self :  List[str]						,							A_ :  List[str]=None						,							A_ :  List[Any]=None						,							A_ :  Dict=None						,							A_ :  Tuple="max_length"						,							A_ :  int="np"						,							**A_ :  Union[str, Any]  )       ->     Union[str, Any]:

       """simple docstring"""






       if text is None and query_images is None and images is None:
             raise ValueError(
                 'You have to specify at least one text or query image or image. All three cannot be none.'  )

       if text is not None:
             if isinstance(A_						,							A_  ) or (isinstance(A_						,							A_  ) and not isinstance(text[0]						,							A_  )):
                   lowerCamelCase_							=   [self.tokenizer(A_						,							padding=A_						,							return_tensors=A_						,							**A_  )]

             elif isinstance(A_						,							A_  ) and isinstance(text[0]						,							A_  ):
                   lowerCamelCase_							=   []

                   # Maximum number of queries across batch
                   lowerCamelCase_							=   max([len(A_  ) for t in text]  )

                   # Pad all batch samples to max number of text queries
                   for t in text:
                         if len(A_  ) != max_num_queries:
                               lowerCamelCase_							=   t + [' '] * (max_num_queries - len(A_  ))

                         lowerCamelCase_							=   self.tokenizer(A_						,							padding=A_						,							return_tensors=A_						,							**A_  )
                         encodings.append(A_  )
             else:
                   raise TypeError('Input text should be a string, a list of strings or a nested list of strings'  )

             if return_tensors == "np":
                   lowerCamelCase_							=   np.concatenate([encoding['input_ids'] for encoding in encodings]						,							axis=0  )
                   lowerCamelCase_							=   np.concatenate([encoding['attention_mask'] for encoding in encodings]						,							axis=0  )

             elif return_tensors == "jax" and is_flax_available():
                   import jax.numpy as jnp

                   lowerCamelCase_							=   jnp.concatenate([encoding['input_ids'] for encoding in encodings]						,							axis=0  )
                   lowerCamelCase_							=   jnp.concatenate([encoding['attention_mask'] for encoding in encodings]						,							axis=0  )

             elif return_tensors == "pt" and is_torch_available():
                   import torch

                   lowerCamelCase_							=   torch.cat([encoding['input_ids'] for encoding in encodings]						,							dim=0  )
                   lowerCamelCase_							=   torch.cat([encoding['attention_mask'] for encoding in encodings]						,							dim=0  )

             elif return_tensors == "tf" and is_tf_available():
                   import tensorflow as tf

                   lowerCamelCase_							=   tf.stack([encoding['input_ids'] for encoding in encodings]						,							axis=0  )
                   lowerCamelCase_							=   tf.stack([encoding['attention_mask'] for encoding in encodings]						,							axis=0  )

             else:
                   raise ValueError('Target return tensor type could not be returned'  )

             lowerCamelCase_							=   BatchEncoding()
             lowerCamelCase_							=   input_ids
             lowerCamelCase_							=   attention_mask

       if query_images is not None:
             lowerCamelCase_							=   BatchEncoding()
             lowerCamelCase_							=   self.image_processor(
                 A_						,							return_tensors=A_						,							**A_  ).pixel_values
             lowerCamelCase_							=   query_pixel_values

       if images is not None:
             lowerCamelCase_							=   self.image_processor(A_						,							return_tensors=A_						,							**A_  )

       if text is not None and images is not None:
             lowerCamelCase_							=   image_features.pixel_values
             return encoding
       elif query_images is not None and images is not None:
             lowerCamelCase_							=   image_features.pixel_values
             return encoding
       elif text is not None or query_images is not None:
             return encoding
       else:
             return BatchEncoding(data=dict(**A_  )						,							tensor_type=A_  )

 def     a__			(    self :  Tuple						,							*A_ :  Dict						,							**A_ :  Dict  )       ->     Any:

       """simple docstring"""






       return self.image_processor.post_process(*A_						,							**A_  )

 def     a__			(    self :  List[str]						,							*A_ :  Any						,							**A_ :  List[Any]  )       ->     Optional[int]:

       """simple docstring"""






       return self.image_processor.post_process_object_detection(*A_						,							**A_  )

 def     a__			(    self :  Any						,							*A_ :  str						,							**A_ :  List[Any]  )       ->     Any:

       """simple docstring"""






       return self.image_processor.post_process_image_guided_detection(*A_						,							**A_  )

 def     a__			(    self :  Union[str, Any]						,							*A_ :  Any						,							**A_ :  Union[str, Any]  )       ->     str:

       """simple docstring"""






       return self.tokenizer.batch_decode(*A_						,							**A_  )

 def     a__			(    self :  Optional[int]						,							*A_ :  List[Any]						,							**A_ :  int  )       ->     int:

       """simple docstring"""






       return self.tokenizer.decode(*A_						,							**A_  )

 @property
 def     a__			(    self :  List[Any]  )       ->     List[Any]:

       """simple docstring"""






       warnings.warn(
           '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'						,							A_						,							)
       return self.image_processor_class





 @property
 def     a__			(    self :  str  )       ->     List[str]:

       """simple docstring"""






       warnings.warn(
           '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'						,							A_						,							)
       return self.image_processor



