





import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
     from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor

class   A							:



      def __init__(						self:    List[str]		,	_lowerCAmelCase:    Tuple		,	_lowerCAmelCase:    Dict=13		,	_lowerCAmelCase:    Optional[Any]=32		,	_lowerCAmelCase:    Optional[int]=3		,	_lowerCAmelCase:    List[str]=4		,	_lowerCAmelCase:    Any=[10, 20, 30, 40]		,	_lowerCAmelCase:    Tuple=[2, 2, 3, 2]		,	_lowerCAmelCase:    Tuple=True		,	_lowerCAmelCase:    Any=True		,	_lowerCAmelCase:    Union[str, Any]=37		,	_lowerCAmelCase:    Optional[Any]="gelu"		,	_lowerCAmelCase:    Optional[Any]=10		,	_lowerCAmelCase:    Optional[Any]=0.02		,	_lowerCAmelCase:    List[str]=["stage2", "stage3", "stage4"]		,	_lowerCAmelCase:    List[Any]=[2, 3, 4]		,	_lowerCAmelCase:    Any=None		,	)    ->     Union[str, Any]:
         '''simple docstring'''

         UpperCAmelCase_           =parent
         UpperCAmelCase_           =batch_size
         UpperCAmelCase_           =image_size
         UpperCAmelCase_           =num_channels
         UpperCAmelCase_           =num_stages
         UpperCAmelCase_           =hidden_sizes
         UpperCAmelCase_           =depths
         UpperCAmelCase_           =is_training
         UpperCAmelCase_           =use_labels
         UpperCAmelCase_           =intermediate_size
         UpperCAmelCase_           =hidden_act
         UpperCAmelCase_           =num_labels
         UpperCAmelCase_           =initializer_range
         UpperCAmelCase_           =out_features
         UpperCAmelCase_           =out_indices
         UpperCAmelCase_           =scope



      def 						lowerCAmelCase__     (						self:    Optional[int]							)    ->     Tuple:
         '''simple docstring'''

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

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

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



      def 						lowerCAmelCase__     (						self:    int							)    ->     List[str]:
         '''simple docstring'''

         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=_lowerCAmelCase		,	initializer_range=self.initializer_range		,	out_features=self.out_features		,	out_indices=self.out_indices		,	num_labels=self.num_labels		,	)



      def 						lowerCAmelCase__     (						self:    List[Any]		,	_lowerCAmelCase:    Dict		,	_lowerCAmelCase:    List[Any]		,	_lowerCAmelCase:    List[Any]							)    ->     str:
         '''simple docstring'''

         UpperCAmelCase_           =ConvNextModel(config=_lowerCAmelCase							)
         model.to(_lowerCAmelCase							)
         model.eval()
         UpperCAmelCase_           =model(_lowerCAmelCase							)
         # 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 						lowerCAmelCase__     (						self:    int		,	_lowerCAmelCase:    List[str]		,	_lowerCAmelCase:    List[Any]		,	_lowerCAmelCase:    Any							)    ->     int:
         '''simple docstring'''

         UpperCAmelCase_           =ConvNextForImageClassification(_lowerCAmelCase							)
         model.to(_lowerCAmelCase							)
         model.eval()
         UpperCAmelCase_           =model(_lowerCAmelCase		,	labels=_lowerCAmelCase							)
         self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.num_labels)							)



      def 						lowerCAmelCase__     (						self:    int		,	_lowerCAmelCase:    List[str]		,	_lowerCAmelCase:    Dict		,	_lowerCAmelCase:    List[Any]							)    ->     Tuple:
         '''simple docstring'''

         UpperCAmelCase_           =ConvNextBackbone(config=_lowerCAmelCase							)
         model.to(_lowerCAmelCase							)
         model.eval()
         UpperCAmelCase_           =model(_lowerCAmelCase							)

         # verify hidden states
         self.parent.assertEqual(len(result.feature_maps							)		,	len(config.out_features							)							)
         self.parent.assertListEqual(list(result.feature_maps[0].shape							)		,	[self.batch_size, self.hidden_sizes[1], 4, 4]							)

         # verify channels
         self.parent.assertEqual(len(model.channels							)		,	len(config.out_features							)							)
         self.parent.assertListEqual(model.channels		,	config.hidden_sizes[1:]							)

         # verify backbone works with out_features=None
         UpperCAmelCase_           =None
         UpperCAmelCase_           =ConvNextBackbone(config=_lowerCAmelCase							)
         model.to(_lowerCAmelCase							)
         model.eval()
         UpperCAmelCase_           =model(_lowerCAmelCase							)

         # verify feature maps
         self.parent.assertEqual(len(result.feature_maps							)		,	1							)
         self.parent.assertListEqual(list(result.feature_maps[0].shape							)		,	[self.batch_size, self.hidden_sizes[-1], 1, 1]							)

         # verify channels
         self.parent.assertEqual(len(model.channels							)		,	1							)
         self.parent.assertListEqual(model.channels		,	[config.hidden_sizes[-1]]							)






      def 						lowerCAmelCase__     (						self:    Optional[Any]							)    ->     int:
         '''simple docstring'''

         UpperCAmelCase_           =self.prepare_config_and_inputs()
         UpperCAmelCase_    ,							UpperCAmelCase_    ,							UpperCAmelCase_           =config_and_inputs
         UpperCAmelCase_           ={"pixel_values": pixel_values}
         return config, inputs_dict

@require_torch
class   A							(						__lowercase		,   __lowercase		,   unittest.TestCase    ):
      _snake_case				  =(
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      _snake_case				  =(
          {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      _snake_case				  =True
      _snake_case				  =False
      _snake_case				  =False
      _snake_case				  =False
      _snake_case				  =False



      def 						lowerCAmelCase__     (						self:    Dict							)    ->     Dict:
         '''simple docstring'''

         UpperCAmelCase_           =ConvNextModelTester(self							)
         UpperCAmelCase_           =ConfigTester(self		,	config_class=_lowerCAmelCase		,	has_text_modality=_lowerCAmelCase		,	hidden_size=37							)



      def 						lowerCAmelCase__     (						self:    str							)    ->     str:
         '''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:    int							)    ->     str:
         '''simple docstring'''

         return



      @unittest.skip(reason="ConvNext does not use inputs_embeds"							)
      def 						lowerCAmelCase__     (						self:    Union[str, Any]							)    ->     List[str]:
         '''simple docstring'''

         pass



      @unittest.skip(reason="ConvNext does not support input and output embeddings"							)
      def 						lowerCAmelCase__     (						self:    Dict							)    ->     Optional[Any]:
         '''simple docstring'''

         pass



      @unittest.skip(reason="ConvNext does not use feedforward chunking"							)
      def 						lowerCAmelCase__     (						self:    List[Any]							)    ->     Any:
         '''simple docstring'''

         pass



      def 						lowerCAmelCase__     (						self:    Union[str, Any]							)    ->     List[str]:
         '''simple docstring'''

         UpperCAmelCase_    ,							UpperCAmelCase_           =self.model_tester.prepare_config_and_inputs_for_common()

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

            UpperCAmelCase_           =["pixel_values"]
            self.assertListEqual(arg_names[:1]		,	_lowerCAmelCase							)



      def 						lowerCAmelCase__     (						self:    Any							)    ->     Optional[int]:
         '''simple docstring'''

         UpperCAmelCase_           =self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCAmelCase							)



      def 						lowerCAmelCase__     (						self:    List[Any]							)    ->     int:
         '''simple docstring'''

         UpperCAmelCase_           =self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_backbone(*_lowerCAmelCase							)



      def 						lowerCAmelCase__     (						self:    List[Any]							)    ->     Any:
         '''simple docstring'''

         def check_hidden_states_output(_lowerCAmelCase:    List[Any]		,	_lowerCAmelCase:    Optional[Any]		,	_lowerCAmelCase:    int							):
            UpperCAmelCase_           =model_class(_lowerCAmelCase							)
            model.to(_lowerCAmelCase							)
            model.eval()

            with torch.no_grad():
               UpperCAmelCase_           =model(**self._prepare_for_class(_lowerCAmelCase		,	_lowerCAmelCase							)							)

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

            UpperCAmelCase_           =self.model_tester.num_stages
            self.assertEqual(len(_lowerCAmelCase							)		,	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]		,	)

         UpperCAmelCase_    ,							UpperCAmelCase_           =self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase_           =True
            check_hidden_states_output(_lowerCAmelCase		,	_lowerCAmelCase		,	_lowerCAmelCase							)

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

            check_hidden_states_output(_lowerCAmelCase		,	_lowerCAmelCase		,	_lowerCAmelCase							)



      def 						lowerCAmelCase__     (						self:    str							)    ->     Tuple:
         '''simple docstring'''

         UpperCAmelCase_           =self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase							)






      @slow
      def 						lowerCAmelCase__     (						self:    str							)    ->     List[str]:
         '''simple docstring'''

         for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            UpperCAmelCase_           =ConvNextModel.from_pretrained(_lowerCAmelCase							)
            self.assertIsNotNone(_lowerCAmelCase							)




def      a__			(       ):






   '''simple docstring'''






   UpperCAmelCase_           =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
   return image

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



      @cached_property
      def 						lowerCAmelCase__     (						self:    Tuple							)    ->     List[Any]:
         '''simple docstring'''

         return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224"							) if is_vision_available() else None






      @slow
      def 						lowerCAmelCase__     (						self:    List[Any]							)    ->     List[Any]:
         '''simple docstring'''

         UpperCAmelCase_           =ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"							).to(_lowerCAmelCase							)

         UpperCAmelCase_           =self.default_image_processor
         UpperCAmelCase_           =prepare_img()
         UpperCAmelCase_           =image_processor(images=_lowerCAmelCase		,	return_tensors="pt"							).to(_lowerCAmelCase							)

         # forward pass
         with torch.no_grad():
            UpperCAmelCase_           =model(**_lowerCAmelCase							)

         # verify the logits
         UpperCAmelCase_           =torch.Size((1, 1000)							)
         self.assertEqual(outputs.logits.shape		,	_lowerCAmelCase							)

         UpperCAmelCase_           =torch.tensor([-0.02_60, -0.47_39, 0.19_11]							).to(_lowerCAmelCase							)

         self.assertTrue(torch.allclose(outputs.logits[0, :3]		,	_lowerCAmelCase		,	atol=1e-4							)							)

@require_torch
class   A							(						unittest.TestCase		,   __lowercase    ):
      _snake_case				  =(ConvNextBackbone,) if is_torch_available() else ()
      _snake_case				  =ConvNextConfig

      _snake_case				  =False



      def 						lowerCAmelCase__     (						self:    List[Any]							)    ->     Dict:
         '''simple docstring'''

         UpperCAmelCase_           =ConvNextModelTester(self							)





import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF

import datasets


SCREAMING_SNAKE_CASE		:     Tuple         =	"\\n@inproceedings{popovic-2015-chrf,\n    title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n    author = \"Popovi{\'c}, Maja\",\n    booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n    month = sep,\n    year = \"2015\",\n    address = \"Lisbon, Portugal\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://aclanthology.org/W15-3049\",\n    doi = \"10.18653/v1/W15-3049\",\n    pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n    title = \"chr{F}++: words helping character n-grams\",\n    author = \"Popovi{\'c}, Maja\",\n    booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n    month = sep,\n    year = \"2017\",\n    address = \"Copenhagen, Denmark\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://aclanthology.org/W17-4770\",\n    doi = \"10.18653/v1/W17-4770\",\n    pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n    title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n    author = \"Post, Matt\",\n    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n    month = oct,\n    year = \"2018\",\n    address = \"Belgium, Brussels\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/W18-6319\",\n    pages = \"186--191\",\n}\n"

SCREAMING_SNAKE_CASE		:     Tuple         =	"\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n"

SCREAMING_SNAKE_CASE		:     Optional[int]         =	"\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n    predictions (list of str): The predicted sentences.\n    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n    char_order (int): Character n-gram order. Defaults to `6`.\n    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n    eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n    to reference chrF++.py, NLTK and Moses implementations. If `False`,\n    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n    'score' (float): The chrF (chrF++) score,\n    'char_order' (int): The character n-gram order,\n    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n    'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n    Example 1--a simple example of calculating chrF:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction, references=reference)\n        >>> print(results)\n        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2)\n        >>> print(results)\n        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2,\n        ...                         lowercase=True)\n        >>> print(results)\n        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n"

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





						def        A_							(self						)				->				Dict:
												if version.parse(scb.__version__						) < version.parse("""1.4.12"""						):
																		raise ImportWarning(
																		    """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"""
																		    """You can install it with `pip install \"sacrebleu>=1.4.12\"`."""						)
												return datasets.MetricInfo(
												    description=_DESCRIPTION			,     citation=_CITATION			,     homepage="""https://github.com/mjpost/sacreBLEU#chrf--chrf"""			,     inputs_description=_KWARGS_DESCRIPTION			,     features=datasets.Features(
												        {
												            """predictions""": datasets.Value("""string"""			,     id="""sequence"""						),
												            """references""": datasets.Sequence(datasets.Value("""string"""			,     id="""sequence"""						)			,     id="""references"""						),
												        }						)			,     codebase_urls=["""https://github.com/mjpost/sacreBLEU#chrf--chrf"""]			,     reference_urls=[
												        """https://github.com/m-popovic/chrF""",
												    ]			,     )





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase = CHRF.CHAR_ORDER			,     __UpperCamelCase = CHRF.WORD_ORDER			,     __UpperCamelCase = CHRF.BETA			,     __UpperCamelCase = False			,     __UpperCamelCase = False			,     __UpperCamelCase = False			,     )				->				List[Any]:
												UpperCamelCase_		:							List[str]  =		len(references[0]						)
												if any(len(__UpperCamelCase						) != references_per_prediction for refs in references						):
																		raise ValueError("""Sacrebleu requires the same number of references for each prediction"""						)
												UpperCamelCase_		:							Optional[Any]  =		[[refs[i] for refs in references] for i in range(__UpperCamelCase						)]

												UpperCamelCase_		:							List[Any]  =		CHRF(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)
												UpperCamelCase_		:							int  =		sb_chrf.corpus_score(__UpperCamelCase			,     __UpperCamelCase						)

												return {
												    "score": output.score,
												    "char_order": output.char_order,
												    "word_order": output.word_order,
												    "beta": output.beta,
												}






