

'''simple docstring'''
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  ):


   def __init__(			self      ,    _UpperCamelCase      ,    _UpperCamelCase=3      ,    _UpperCamelCase=32      ,    _UpperCamelCase=3      ,    _UpperCamelCase=10      ,    _UpperCamelCase=[10, 20, 30, 40]      ,    _UpperCamelCase=[1, 1, 2, 1]      ,    _UpperCamelCase=True      ,    _UpperCamelCase=True      ,    _UpperCamelCase="relu"      ,    _UpperCamelCase=3      ,    _UpperCamelCase=None      ,    ):





      """simple docstring"""





      _lowercase      :				int      					=       parent
      _lowercase      :				Optional[Any]      					=       batch_size
      _lowercase      :				str      					=       image_size
      _lowercase      :				Union[str, Any]      					=       num_channels
      _lowercase      :				Optional[Any]      					=       embeddings_size
      _lowercase      :				Optional[int]      					=       hidden_sizes
      _lowercase      :				Optional[Any]      					=       depths
      _lowercase      :				Optional[Any]      					=       is_training
      _lowercase      :				Union[str, Any]      					=       use_labels
      _lowercase      :				Tuple      					=       hidden_act
      _lowercase      :				str      					=       num_labels
      _lowercase      :				Union[str, Any]      					=       scope
      _lowercase      :				Union[str, Any]      					=       len(_UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				List[Any]      					=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

      _lowercase      :				Tuple      					=       self.get_config()

      return config, pixel_values


   def 						_lowerCamelCase       (			self  ):





      """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 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       FlaxRegNetModel(config=_UpperCamelCase  )
      _lowercase      :				Dict      					=       model(_UpperCamelCase  )

      # 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 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       self.num_labels
      _lowercase      :				Optional[Any]      					=       FlaxRegNetForImageClassification(config=_UpperCamelCase  )
      _lowercase      :				str      					=       model(_UpperCamelCase  )
      self.parent.assertEqual(result.logits.shape      ,    (self.batch_size, self.num_labels)  )






   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Union[str, Any]      					=       self.prepare_config_and_inputs()
      _lowercase					,				_lowercase      :				Union[str, Any]      					=       config_and_inputs
      _lowercase      :				List[Any]      					=       {"pixel_values": pixel_values}
      return config, inputs_dict




@require_flax
class        a__  (							lowerCamelCase_  ,				unittest.TestCase  ):
   _SCREAMING_SNAKE_CASE   :					str     	=							(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

   _SCREAMING_SNAKE_CASE   :					List[str]     	=							False
   _SCREAMING_SNAKE_CASE   :					str     	=							False
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							False


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				str      					=       FlaxRegNetModelTester(self  )
      _lowercase      :				Union[str, Any]      					=       ConfigTester(self      ,    config_class=_UpperCamelCase      ,    has_text_modality=_UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """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 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      return


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				List[Any]      					=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				int      					=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase  )


   @unittest.skip(reason="RegNet does not use inputs_embeds"  )
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      pass


   @unittest.skip(reason="RegNet does not support input and output embeddings"  )
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      pass


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase					,				_lowercase      :				Tuple      					=       self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         _lowercase      :				str      					=       model_class(_UpperCamelCase  )
         _lowercase      :				Optional[Any]      					=       inspect.signature(model.__call__  )
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         _lowercase      :				List[Any]      					=       [*signature.parameters.keys()]

         _lowercase      :				Any      					=       ["pixel_values"]
         self.assertListEqual(arg_names[:1]      ,    _UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      def check_hidden_states_output(_UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase  ):
         _lowercase      :				Optional[int]      					=       model_class(_UpperCamelCase  )

         _lowercase      :				Union[str, Any]      					=       model(**self._prepare_for_class(_UpperCamelCase      ,    _UpperCamelCase  )  )

         _lowercase      :				str      					=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         _lowercase      :				Dict      					=       self.model_tester.num_stages
         self.assertEqual(len(_UpperCamelCase  )      ,    expected_num_stages + 1  )

      _lowercase					,				_lowercase      :				List[Any]      					=       self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         _lowercase      :				Optional[Any]      					=       True
         check_hidden_states_output(_UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase  )

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         _lowercase      :				Any      					=       True

         check_hidden_states_output(_UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase  )






   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase					,				_lowercase      :				List[Any]      					=       self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         with self.subTest(model_class.__name__  ):
            _lowercase      :				Any      					=       self._prepare_for_class(_UpperCamelCase      ,    _UpperCamelCase  )
            _lowercase      :				Optional[int]      					=       model_class(_UpperCamelCase  )

            @jax.jit
            def model_jitted(_UpperCamelCase      ,    **_UpperCamelCase  ):
               return model(pixel_values=_UpperCamelCase      ,    **_UpperCamelCase  )

            with self.subTest("JIT Enabled"  ):
               _lowercase      :				str      					=       model_jitted(**_UpperCamelCase  ).to_tuple()

            with self.subTest("JIT Disabled"  ):
               with jax.disable_jit():
                  _lowercase      :				str      					=       model_jitted(**_UpperCamelCase  ).to_tuple()

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







def  _A		(     )      ->     List[Any]:
   _lowercase      :				Dict      					=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
   return image


@require_flax
class        a__  (							unittest.TestCase  ):


   @cached_property
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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






   @slow
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Optional[int]      					=       FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040"  )

      _lowercase      :				Tuple      					=       self.default_image_processor
      _lowercase      :				Union[str, Any]      					=       prepare_img()
      _lowercase      :				Union[str, Any]      					=       image_processor(images=_UpperCamelCase      ,    return_tensors="np"  )

      _lowercase      :				List[str]      					=       model(**_UpperCamelCase  )

      # verify the logits
      _lowercase      :				List[str]      					=       (1, 1000)
      self.assertEqual(outputs.logits.shape      ,    _UpperCamelCase  )

      _lowercase      :				Tuple      					=       jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]  )

      self.assertTrue(jnp.allclose(outputs.logits[0, :3]      ,    _UpperCamelCase      ,    atol=1E-4  )  )









'''simple docstring'''
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__  (							lowerCamelCase_  ):
   _SCREAMING_SNAKE_CASE   :					List[Any]     	=							['image_processor', 'tokenizer']
   _SCREAMING_SNAKE_CASE   :					str     	=							'OwlViTImageProcessor'
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							('CLIPTokenizer', 'CLIPTokenizerFast')


   def __init__(			self      ,    _UpperCamelCase=None      ,    _UpperCamelCase=None      ,    **_UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       None
      if "feature_extractor" in kwargs:
         warnings.warn(
             "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
             " instead."      ,    _UpperCamelCase      ,    )
         _lowercase      :				Optional[int]      					=       kwargs.pop("feature_extractor"  )

      _lowercase      :				str      					=       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__(_UpperCamelCase      ,    _UpperCamelCase  )


   def __call__(			self      ,    _UpperCamelCase=None      ,    _UpperCamelCase=None      ,    _UpperCamelCase=None      ,    _UpperCamelCase="max_length"      ,    _UpperCamelCase="np"      ,    **_UpperCamelCase  ):





      """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(_UpperCamelCase      ,    _UpperCamelCase  ) or (isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) and not isinstance(text[0]      ,    _UpperCamelCase  )):
            _lowercase      :				int      					=       [self.tokenizer(_UpperCamelCase      ,    padding=_UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  )]

         elif isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) and isinstance(text[0]      ,    _UpperCamelCase  ):
            _lowercase      :				str      					=       []

            # Maximum number of queries across batch
            _lowercase      :				str      					=       max([len(_UpperCamelCase  ) for t in text]  )

            # Pad all batch samples to max number of text queries
            for t in text:
               if len(_UpperCamelCase  ) != max_num_queries:
                  _lowercase      :				List[Any]      					=       t + [" "] * (max_num_queries - len(_UpperCamelCase  ))

               _lowercase      :				Tuple      					=       self.tokenizer(_UpperCamelCase      ,    padding=_UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  )
               encodings.append(_UpperCamelCase  )
         else:
            raise TypeError("Input text should be a string, a list of strings or a nested list of strings"  )

         if return_tensors == "np":
            _lowercase      :				List[Any]      					=       np.concatenate([encoding["input_ids"] for encoding in encodings]      ,    axis=0  )
            _lowercase      :				Optional[Any]      					=       np.concatenate([encoding["attention_mask"] for encoding in encodings]      ,    axis=0  )

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

            _lowercase      :				Union[str, Any]      					=       jnp.concatenate([encoding["input_ids"] for encoding in encodings]      ,    axis=0  )
            _lowercase      :				int      					=       jnp.concatenate([encoding["attention_mask"] for encoding in encodings]      ,    axis=0  )

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

            _lowercase      :				int      					=       torch.cat([encoding["input_ids"] for encoding in encodings]      ,    dim=0  )
            _lowercase      :				Dict      					=       torch.cat([encoding["attention_mask"] for encoding in encodings]      ,    dim=0  )

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

            _lowercase      :				Optional[int]      					=       tf.stack([encoding["input_ids"] for encoding in encodings]      ,    axis=0  )
            _lowercase      :				List[str]      					=       tf.stack([encoding["attention_mask"] for encoding in encodings]      ,    axis=0  )

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

         _lowercase      :				Optional[int]      					=       BatchEncoding()
         _lowercase      :				List[Any]      					=       input_ids
         _lowercase      :				Dict      					=       attention_mask

      if query_images is not None:
         _lowercase      :				int      					=       BatchEncoding()
         _lowercase      :				Any      					=       self.image_processor(
             _UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  ).pixel_values
         _lowercase      :				Any      					=       query_pixel_values

      if images is not None:
         _lowercase      :				str      					=       self.image_processor(_UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  )

      if text is not None and images is not None:
         _lowercase      :				List[Any]      					=       image_features.pixel_values
         return encoding
      elif query_images is not None and images is not None:
         _lowercase      :				Optional[Any]      					=       image_features.pixel_values
         return encoding
      elif text is not None or query_images is not None:
         return encoding
      else:
         return BatchEncoding(data=dict(**_UpperCamelCase  )      ,    tensor_type=_UpperCamelCase  )


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





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


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





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


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





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


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





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


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





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


   @property
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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






   @property
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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






