




import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
 import jax
 import jax.numpy as jnp

 from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor







class   A(						unittest.TestCase       ):



 '''simple docstring'''


 def __init__(    self :  Dict						,							A_ :  Union[str, Any]						,							A_ :  Tuple=3						,							A_ :  Any=32						,							A_ :  Union[str, Any]=3						,							A_ :  str=10						,							A_ :  Tuple=[10, 20, 30, 40]						,							A_ :  Tuple=[1, 1, 2, 1]						,							A_ :  str=True						,							A_ :  str=True						,							A_ :  Optional[int]="relu"						,							A_ :  Dict=3						,							A_ :  Optional[Any]=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 :  Optional[int]  )       ->     Optional[int]:

       """simple docstring"""






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

       lowerCamelCase_							=   self.get_config()

       return config, pixel_values

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

       """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						,							image_size=self.image_size						,							)

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

       """simple docstring"""






       lowerCamelCase_							=   FlaxRegNetModel(config=A_  )
       lowerCamelCase_							=   model(A_  )

       # Output shape (b, c, h, w)
       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[Any]						,							A_ :  Union[str, Any]						,							A_ :  int  )       ->     Any:

       """simple docstring"""






       lowerCamelCase_							=   self.num_labels
       lowerCamelCase_							=   FlaxRegNetForImageClassification(config=A_  )
       lowerCamelCase_							=   model(A_  )
       self.parent.assertEqual(result.logits.shape						,							(self.batch_size, self.num_labels)  )





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

       """simple docstring"""






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







@require_flax
class   A(						UpperCamelCase							,				unittest.TestCase       ):



 '''simple docstring'''


 UpperCamelCase						       =						(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

 UpperCamelCase						       =						False
 UpperCamelCase						       =						False
 UpperCamelCase						       =						False

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

       """simple docstring"""






       lowerCamelCase_							=   FlaxRegNetModelTester(self  )
       lowerCamelCase_							=   ConfigTester(self						,							config_class=A_						,							has_text_modality=A_  )

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

       """simple docstring"""






       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()

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

       """simple docstring"""






       return

 def     a__			(    self :  Tuple  )       ->     str:

       """simple docstring"""






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

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

       """simple docstring"""






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

 @unittest.skip(reason='RegNet does not use inputs_embeds'  )
 def     a__			(    self :  Tuple  )       ->     Tuple:

       """simple docstring"""






       pass

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

       """simple docstring"""






       pass

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

       """simple docstring"""






       lowerCamelCase_					,    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 :  Tuple  )       ->     Any:

       """simple docstring"""






       def check_hidden_states_output(A_ :  int						,							A_ :  Optional[int]						,							A_ :  Tuple  ):
             lowerCamelCase_							=   model_class(A_  )

             lowerCamelCase_							=   model(**self._prepare_for_class(A_						,							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  )

       lowerCamelCase_					,    lowerCamelCase_							=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             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 :  int  )       ->     int:

       """simple docstring"""






       lowerCamelCase_					,    lowerCamelCase_							=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             with self.subTest(model_class.__name__  ):
                   lowerCamelCase_							=   self._prepare_for_class(A_						,							A_  )
                   lowerCamelCase_							=   model_class(A_  )

                   @jax.jit
                   def model_jitted(A_ :  List[Any]						,							**A_ :  List[Any]  ):
                         return model(pixel_values=A_						,							**A_  )

                   with self.subTest('JIT Enabled'  ):
                         lowerCamelCase_							=   model_jitted(**A_  ).to_tuple()

                   with self.subTest('JIT Disabled'  ):
                         with jax.disable_jit():
                               lowerCamelCase_							=   model_jitted(**A_  ).to_tuple()

                   self.assertEqual(len(A_  )						,							len(A_  )  )
                   for jitted_output, output in zip(A_						,							A_  ):
                         self.assertEqual(jitted_output.shape						,							output.shape  )

def       _SCREAMING_SNAKE_CASE      (							):


      '''simple docstring'''



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







@require_flax
class   A(						unittest.TestCase       ):



 '''simple docstring'''


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

       """simple docstring"""






       return AutoImageProcessor.from_pretrained('facebook/regnet-y-040'  ) if is_vision_available() else None





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

       """simple docstring"""






       lowerCamelCase_							=   FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040'  )

       lowerCamelCase_							=   self.default_image_processor
       lowerCamelCase_							=   prepare_img()
       lowerCamelCase_							=   image_processor(images=A_						,							return_tensors='np'  )

       lowerCamelCase_							=   model(**A_  )

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

       lowerCamelCase_							=   jnp.array([-0.4180, -1.5051, -3.4836]  )

       self.assertTrue(jnp.allclose(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



