

from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
  from PIL import Image

  from transformers import ConvNextImageProcessor







class  UpperCamelCase_      :


  """simple docstring"""



  def __init__(						self     :					str  ,	A_     :					Dict  ,	A_     :					List[Any]=13  ,	A_     :					str=32  ,	A_     :					Tuple=3  ,	A_     :					Optional[int]=4  ,	A_     :					Dict=[10, 20, 30, 40]  ,	A_     :					List[str]=[2, 2, 3, 2]  ,	A_     :					Optional[int]=True  ,	A_     :					Any=True  ,	A_     :					List[str]=37  ,	A_     :					int="gelu"  ,	A_     :					List[Any]=10  ,	A_     :					int=0.02  ,	A_     :					Union[str, Any]=3  ,	A_     :					Tuple=None  ,	)       ->			Any:
      SCREAMING_SNAKE_CASE__         =    parent
      SCREAMING_SNAKE_CASE__         =    batch_size
      SCREAMING_SNAKE_CASE__         =    image_size
      SCREAMING_SNAKE_CASE__         =    num_channels
      SCREAMING_SNAKE_CASE__         =    num_stages
      SCREAMING_SNAKE_CASE__         =    hidden_sizes
      SCREAMING_SNAKE_CASE__         =    depths
      SCREAMING_SNAKE_CASE__         =    is_training
      SCREAMING_SNAKE_CASE__         =    use_labels
      SCREAMING_SNAKE_CASE__         =    intermediate_size
      SCREAMING_SNAKE_CASE__         =    hidden_act
      SCREAMING_SNAKE_CASE__         =    type_sequence_label_size
      SCREAMING_SNAKE_CASE__         =    initializer_range
      SCREAMING_SNAKE_CASE__         =    scope



  def   _UpperCamelCase     (						self     :					Tuple						)       ->			Optional[Any]:
      SCREAMING_SNAKE_CASE__         =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

      SCREAMING_SNAKE_CASE__         =    None
      if self.use_labels:
          SCREAMING_SNAKE_CASE__         =    ids_tensor([self.batch_size]  ,	self.type_sequence_label_size						)

      SCREAMING_SNAKE_CASE__         =    self.get_config()

      return config, pixel_values, labels



  def   _UpperCamelCase     (						self     :					List[Any]						)       ->			List[str]:
      return ConvNextConfig(
          num_channels=self.num_channels  ,	hidden_sizes=self.hidden_sizes  ,	depths=self.depths  ,	num_stages=self.num_stages  ,	hidden_act=self.hidden_act  ,	is_decoder=A_  ,	initializer_range=self.initializer_range  ,	)



  def   _UpperCamelCase     (						self     :					str  ,	A_     :					int  ,	A_     :					str  ,	A_     :					Optional[Any]						)       ->			List[Any]:
      SCREAMING_SNAKE_CASE__         =    TFConvNextModel(config=A_						)
      SCREAMING_SNAKE_CASE__         =    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   _UpperCamelCase     (						self     :					Tuple  ,	A_     :					Optional[Any]  ,	A_     :					Dict  ,	A_     :					Dict						)       ->			Optional[int]:
      SCREAMING_SNAKE_CASE__         =    self.type_sequence_label_size
      SCREAMING_SNAKE_CASE__         =    TFConvNextForImageClassification(A_						)
      SCREAMING_SNAKE_CASE__         =    model(A_  ,	labels=A_  ,	training=A_						)
      self.parent.assertEqual(result.logits.shape  ,	(self.batch_size, self.type_sequence_label_size)						)







  def   _UpperCamelCase     (						self     :					int						)       ->			int:
      SCREAMING_SNAKE_CASE__         =    self.prepare_config_and_inputs()
      SCREAMING_SNAKE_CASE__  ,		SCREAMING_SNAKE_CASE__  ,		SCREAMING_SNAKE_CASE__         =    config_and_inputs
      SCREAMING_SNAKE_CASE__         =    {"pixel_values": pixel_values}
      return config, inputs_dict







@require_tf
class  UpperCamelCase_      (	_snake_case		,  _snake_case		,  unittest.TestCase      ):


  """simple docstring"""
  SCREAMING_SNAKE_CASE__					:			Optional[int]					    =   (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
  SCREAMING_SNAKE_CASE__					:			List[str]					    =   (
      {"""feature-extraction""": TFConvNextModel, """image-classification""": TFConvNextForImageClassification}
      if is_tf_available()
      else {}
  )

  SCREAMING_SNAKE_CASE__					:			Dict					    =   False
  SCREAMING_SNAKE_CASE__					:			Optional[int]					    =   False
  SCREAMING_SNAKE_CASE__					:			List[str]					    =   False
  SCREAMING_SNAKE_CASE__					:			List[Any]					    =   False
  SCREAMING_SNAKE_CASE__					:			Any					    =   False



  def   _UpperCamelCase     (						self     :					Optional[Any]						)       ->			Tuple:
      SCREAMING_SNAKE_CASE__         =    TFConvNextModelTester(self						)
      SCREAMING_SNAKE_CASE__         =    ConfigTester(
          self  ,	config_class=A_  ,	has_text_modality=A_  ,	hidden_size=37  ,	)



  @unittest.skip(reason="ConvNext does not use inputs_embeds"						)
  def   _UpperCamelCase     (						self     :					List[Any]						)       ->			Any:
      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   _UpperCamelCase     (						self     :					Union[str, Any]						)       ->			List[Any]:
      super().test_keras_fit()



  @unittest.skip(reason="ConvNext does not support input and output embeddings"						)
  def   _UpperCamelCase     (						self     :					int						)       ->			List[Any]:
      pass



  def   _UpperCamelCase     (						self     :					str						)       ->			int:
      SCREAMING_SNAKE_CASE__  ,		SCREAMING_SNAKE_CASE__         =    self.model_tester.prepare_config_and_inputs_for_common()

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

          SCREAMING_SNAKE_CASE__         =    ["pixel_values"]
          self.assertListEqual(arg_names[:1]  ,	A_						)



  def   _UpperCamelCase     (						self     :					Tuple						)       ->			Optional[int]:
      SCREAMING_SNAKE_CASE__         =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A_						)



  @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."  ,	)
  def   _UpperCamelCase     (						self     :					Union[str, Any]						)       ->			int:
      super().test_dataset_conversion()



  def   _UpperCamelCase     (						self     :					Union[str, Any]						)       ->			List[Any]:
      def check_hidden_states_output(A_     :					Tuple  ,	A_     :					List[Any]  ,	A_     :					Optional[int]						):
          SCREAMING_SNAKE_CASE__         =    model_class(A_						)

          SCREAMING_SNAKE_CASE__         =    model(**self._prepare_for_class(A_  ,	A_						)						)
          SCREAMING_SNAKE_CASE__         =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          SCREAMING_SNAKE_CASE__         =    self.model_tester.num_stages
          self.assertEqual(len(A_						)  ,	expected_num_stages + 1						)

          # ConvNext'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 // 4, self.model_tester.image_size // 4]  ,	)

      SCREAMING_SNAKE_CASE__  ,		SCREAMING_SNAKE_CASE__         =    self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          SCREAMING_SNAKE_CASE__         =    True
          check_hidden_states_output(A_  ,	A_  ,	A_						)

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

          check_hidden_states_output(A_  ,	A_  ,	A_						)



  def   _UpperCamelCase     (						self     :					int						)       ->			Optional[Any]:
      SCREAMING_SNAKE_CASE__  ,		SCREAMING_SNAKE_CASE__         =    self.model_tester.prepare_config_and_inputs_for_common()

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

          def recursive_check(A_     :					Dict  ,	A_     :					Optional[Any]						):
              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:
          SCREAMING_SNAKE_CASE__         =    model_class(A_						)

          SCREAMING_SNAKE_CASE__         =    self._prepare_for_class(A_  ,	A_						)
          SCREAMING_SNAKE_CASE__         =    self._prepare_for_class(A_  ,	A_						)
          check_equivalence(A_  ,	A_  ,	A_						)

          SCREAMING_SNAKE_CASE__         =    self._prepare_for_class(A_  ,	A_  ,	return_labels=A_						)
          SCREAMING_SNAKE_CASE__         =    self._prepare_for_class(A_  ,	A_  ,	return_labels=A_						)
          check_equivalence(A_  ,	A_  ,	A_						)

          SCREAMING_SNAKE_CASE__         =    self._prepare_for_class(A_  ,	A_						)
          SCREAMING_SNAKE_CASE__         =    self._prepare_for_class(A_  ,	A_						)
          check_equivalence(A_  ,	A_  ,	A_  ,	{"output_hidden_states": True}						)

          SCREAMING_SNAKE_CASE__         =    self._prepare_for_class(A_  ,	A_  ,	return_labels=A_						)
          SCREAMING_SNAKE_CASE__         =    self._prepare_for_class(A_  ,	A_  ,	return_labels=A_						)
          check_equivalence(A_  ,	A_  ,	A_  ,	{"output_hidden_states": True}						)



  def   _UpperCamelCase     (						self     :					int						)       ->			Optional[int]:
      SCREAMING_SNAKE_CASE__         =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*A_						)







  @slow
  def   _UpperCamelCase     (						self     :					Dict						)       ->			Union[str, Any]:
      SCREAMING_SNAKE_CASE__         =    TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"						)
      self.assertIsNotNone(A_						)





def 				__a							(       ):
    SCREAMING_SNAKE_CASE__         =    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
    return image







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


  """simple docstring"""



  @cached_property
  def   _UpperCamelCase     (						self     :					Any						)       ->			int:
      return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224"						) if is_vision_available() else None







  @slow
  def   _UpperCamelCase     (						self     :					Optional[Any]						)       ->			Optional[int]:
      SCREAMING_SNAKE_CASE__         =    TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"						)

      SCREAMING_SNAKE_CASE__         =    self.default_image_processor
      SCREAMING_SNAKE_CASE__         =    prepare_img()
      SCREAMING_SNAKE_CASE__         =    image_processor(images=A_  ,	return_tensors="tf"						)

      # forward pass
      SCREAMING_SNAKE_CASE__         =    model(**A_						)

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

      SCREAMING_SNAKE_CASE__         =    tf.constant([-0.0_260, -0.4_739, 0.1_911]						)

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





from sklearn.metrics import accuracy_score

import datasets


A__										=      "\nAccuracy is the proportion of correct predictions among the total number of cases processed. It can be computed with:\nAccuracy = (TP + TN) / (TP + TN + FP + FN)\n Where:\nTP: True positive\nTN: True negative\nFP: False positive\nFN: False negative\n"


A__										=      "\nArgs:\n    predictions (`list` of `int`): Predicted labels.\n    references (`list` of `int`): Ground truth labels.\n    normalize (`boolean`): If set to False, returns the number of correctly classified samples. Otherwise, returns the fraction of correctly classified samples. Defaults to True.\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n    accuracy (`float` or `int`): Accuracy score. Minimum possible value is 0. Maximum possible value is 1.0, or the number of examples input, if `normalize` is set to `True`.. A higher score means higher accuracy.\n\nExamples:\n\n    Example 1-A simple example\n        >>> accuracy_metric = datasets.load_metric(\"accuracy\")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0])\n        >>> print(results)\n        {'accuracy': 0.5}\n\n    Example 2-The same as Example 1, except with `normalize` set to `False`.\n        >>> accuracy_metric = datasets.load_metric(\"accuracy\")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], normalize=False)\n        >>> print(results)\n        {'accuracy': 3.0}\n\n    Example 3-The same as Example 1, except with `sample_weight` set.\n        >>> accuracy_metric = datasets.load_metric(\"accuracy\")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], sample_weight=[0.5, 2, 0.7, 0.5, 9, 0.4])\n        >>> print(results)\n        {'accuracy': 0.8778625954198473}\n"


A__										=      "\n@article{scikit-learn,\n  title={Scikit-learn: Machine Learning in {P}ython},\n  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n  journal={Journal of Machine Learning Research},\n  volume={12},\n  pages={2825--2830},\n  year={2011}\n}\n"







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,  _KWARGS_DESCRIPTION      )
class  UpperCamelCase_      (	datasets.Metric      ):


  """simple docstring"""



  def   _UpperCamelCase     (						self     :					int						)       ->			List[str]:
      return datasets.MetricInfo(
          description=_DESCRIPTION  ,	citation=_CITATION  ,	inputs_description=_KWARGS_DESCRIPTION  ,	features=datasets.Features(
              {
                  "predictions": datasets.Sequence(datasets.Value("int32"						)						),
                  "references": datasets.Sequence(datasets.Value("int32"						)						),
              }
              if self.config_name == "multilabel"
              else {
                  "predictions": datasets.Value("int32"						),
                  "references": datasets.Value("int32"						),
              }						)  ,	reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html"]  ,	)







  def   _UpperCamelCase     (						self     :					Dict  ,	A_     :					List[Any]  ,	A_     :					Tuple  ,	A_     :					Optional[Any]=True  ,	A_     :					Tuple=None						)       ->			Any:
      return {
          "accuracy": float(
              accuracy_score(A_  ,	A_  ,	normalize=A_  ,	sample_weight=A_						)						)
      }


