



from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
 from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor



class 						lowercase__      :

     """simple docstring"""






     def __init__( self :	str   ,			__a :	List[Any]   ,			__a :	List[Any]=3   ,			__a :	str=3_2   ,			__a :	int=3   ,			__a :	Tuple=1_0   ,			__a :	Any=[1_0, 2_0, 3_0, 4_0]   ,			__a :	Any=[1, 1, 2, 1]   ,			__a :	Tuple=True   ,			__a :	str=True   ,			__a :	List[Any]="relu"   ,			__a :	Optional[int]=3   ,			__a :	List[Any]=None   ,			):
      snake_case__				:							Tuple      							= parent
      snake_case__				:							Any      							= batch_size
      snake_case__				:							Any      							= image_size
      snake_case__				:							List[Any]      							= num_channels
      snake_case__				:							Union[str, Any]      							= embeddings_size
      snake_case__				:							Any      							= hidden_sizes
      snake_case__				:							str      							= depths
      snake_case__				:							int      							= is_training
      snake_case__				:							Union[str, Any]      							= use_labels
      snake_case__				:							Union[str, Any]      							= hidden_act
      snake_case__				:							List[str]      							= num_labels
      snake_case__				:							int      							= scope
      snake_case__				:							Optional[Any]      							= len(lowercase__ )


     def 		lowercase   ( self :	List[str] ):
      snake_case__				:							Optional[Any]      							= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

      snake_case__				:							Optional[Any]      							= None
      if self.use_labels:
       snake_case__				:							int      							= ids_tensor([self.batch_size]   ,			self.num_labels )

      snake_case__				:							Union[str, Any]      							= self.get_config()

      return config, pixel_values, labels


     def 		lowercase   ( self :	Tuple ):
      return ResNetConfig(
          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 		lowercase   ( self :	Any   ,			__a :	Any   ,			__a :	Union[str, Any]   ,			__a :	Optional[Any] ):
      snake_case__				:							Optional[Any]      							= TFResNetModel(config=lowercase__ )
      snake_case__				:							Union[str, Any]      							= model(lowercase__ )
      # 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 // 3_2, self.image_size // 3_2)   ,			)


     def 		lowercase   ( self :	List[str]   ,			__a :	Any   ,			__a :	List[Any]   ,			__a :	Tuple ):
      snake_case__				:							Optional[Any]      							= self.num_labels
      snake_case__				:							List[Any]      							= TFResNetForImageClassification(lowercase__ )
      snake_case__				:							List[Any]      							= model(lowercase__   ,			labels=lowercase__ )
      self.parent.assertEqual(result.logits.shape   ,			(self.batch_size, self.num_labels) )


     def 		lowercase   ( self :	int ):
      snake_case__				:							Any      							= self.prepare_config_and_inputs()
      snake_case__							,		snake_case__							,		snake_case__				:							Optional[Any]      							= config_and_inputs
      snake_case__				:							Tuple      							= {"""pixel_values""": pixel_values}
      return config, inputs_dict



@require_tf
class 						lowercase__      (__snake_case						,      __snake_case						,      unittest.TestCase						):

     """simple docstring"""






     __UpperCamelCase    :	int		=       (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
     __UpperCamelCase    :	Union[str, Any]		=       (
         {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
         if is_tf_available()
         else {}
     )

     __UpperCamelCase    :	Any		=       False
     __UpperCamelCase    :	str		=       False
     __UpperCamelCase    :	Any		=       False
     __UpperCamelCase    :	Optional[Any]		=       False
     __UpperCamelCase    :	Dict		=       False


     def 		lowercase   ( self :	Any ):
      snake_case__				:							Any      							= TFResNetModelTester(self )
      snake_case__				:							int      							= ConfigTester(self   ,			config_class=lowercase__   ,			has_text_modality=lowercase__ )


     def 		lowercase   ( self :	str ):
      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 		lowercase   ( self :	Optional[Any] ):
      return


     @unittest.skip(reason="""ResNet does not use inputs_embeds""" )
     def 		lowercase   ( self :	Optional[int] ):
      pass


     @unittest.skip(reason="""ResNet does not support input and output embeddings""" )
     def 		lowercase   ( self :	Optional[int] ):
      pass


     def 		lowercase   ( self :	Dict ):
      snake_case__							,		snake_case__				:							int      							= self.model_tester.prepare_config_and_inputs_for_common()

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

       snake_case__				:							Union[str, Any]      							= ["""pixel_values"""]
       self.assertListEqual(arg_names[:1]   ,			lowercase__ )


     def 		lowercase   ( self :	Tuple ):
      snake_case__				:							Optional[Any]      							= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowercase__ )


     def 		lowercase   ( self :	Tuple ):



      def check_hidden_states_output(__a :	Any   ,			__a :	Any   ,			__a :	Union[str, Any] ):
       snake_case__				:							Union[str, Any]      							= model_class(lowercase__ )
       snake_case__				:							Dict      							= model(**self._prepare_for_class(lowercase__   ,			lowercase__ ) )

       snake_case__				:							Any      							= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

       snake_case__				:							int      							= self.model_tester.num_stages
       self.assertEqual(len(lowercase__ )   ,			expected_num_stages + 1 )

       # ResNet'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]   ,			)

      snake_case__							,		snake_case__				:							List[Any]      							= self.model_tester.prepare_config_and_inputs_for_common()
      snake_case__				:							str      							= ["""basic""", """bottleneck"""]
      for model_class in self.all_model_classes:
       for layer_type in layers_type:
        snake_case__				:							Optional[int]      							= layer_type
        snake_case__				:							List[str]      							= True
        check_hidden_states_output(lowercase__   ,			lowercase__   ,			lowercase__ )

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

        check_hidden_states_output(lowercase__   ,			lowercase__   ,			lowercase__ )


     def 		lowercase   ( self :	Union[str, Any] ):
      snake_case__				:							int      							= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowercase__ )


     @slow
     def 		lowercase   ( self :	int ):



      for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       snake_case__				:							List[Any]      							= TFResNetModel.from_pretrained(lowercase__ )
       self.assertIsNotNone(lowercase__ )

def 	_lowercase	(     ):




 """simple docstring"""




 snake_case__				:							Optional[Any]      							= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
 return image



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

     """simple docstring"""






     @cached_property
     def 		lowercase   ( self :	int ):
      return (
          AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
          if is_vision_available()
          else None
      )


     @slow
     def 		lowercase   ( self :	Optional[Any] ):
      snake_case__				:							List[Any]      							= TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )

      snake_case__				:							Optional[int]      							= self.default_image_processor
      snake_case__				:							Union[str, Any]      							= prepare_img()
      snake_case__				:							int      							= image_processor(images=lowercase__   ,			return_tensors="""tf""" )

      # forward pass
      snake_case__				:							int      							= model(**lowercase__ )

      # verify the logits
      snake_case__				:							Optional[int]      							= tf.TensorShape((1, 1_0_0_0) )
      self.assertEqual(outputs.logits.shape   ,			lowercase__ )

      snake_case__				:							List[Any]      							= tf.constant([-11.1069, -9.7877, -8.3777] )

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







import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


_lowerCamelCase      :					List[str]					    =      version.parse(importlib_metadata.version('''nltk'''))
if NLTK_VERSION >= version.Version('''3.6.4'''):
   from nltk import word_tokenize


_lowerCamelCase      :					Dict					    =      '''\
@inproceedings{banarjee2005,
  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},
  author    = {Banerjee, Satanjeev  and Lavie, Alon},
  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},
  month     = jun,
  year      = {2005},
  address   = {Ann Arbor, Michigan},
  publisher = {Association for Computational Linguistics},
  url       = {https://www.aclweb.org/anthology/W05-0909},
  pages     = {65--72},
}
'''

_lowerCamelCase      :					str					    =      '''\
METEOR, an automatic metric for machine translation evaluation
that is based on a generalized concept of unigram matching between the
machine-produced translation and human-produced reference translations.
Unigrams can be matched based on their surface forms, stemmed forms,
and meanings; furthermore, METEOR can be easily extended to include more
advanced matching strategies. Once all generalized unigram matches
between the two strings have been found, METEOR computes a score for
this matching using a combination of unigram-precision, unigram-recall, and
a measure of fragmentation that is designed to directly capture how
well-ordered the matched words in the machine translation are in relation
to the reference.

METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic
data and 0.331 on the Chinese data. This is shown to be an improvement on
using simply unigram-precision, unigram-recall and their harmonic F1
combination.
'''

_lowerCamelCase      :					Union[str, Any]					    =      '''
Computes METEOR score of translated segments against one or more references.
Args:
    predictions: list of predictions to score. Each prediction
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9
    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3
    gamma: Relative weight assigned to fragmentation penalty. default: 0.5
Returns:
    \'meteor\': meteor score.
Examples:

    >>> meteor = datasets.load_metric(\'meteor\')
    >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]
    >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]
    >>> results = meteor.compute(predictions=predictions, references=references)
    >>> print(round(results["meteor"], 4))
    0.6944
'''





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



       '''simple docstring'''







       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             return datasets.MetricInfo(
                 description=_DESCRIPTION ,   citation=_CITATION ,   inputs_description=_KWARGS_DESCRIPTION ,   features=datasets.Features(
                     {
                         '''predictions''': datasets.Value('''string''' ,   id='''sequence'''     ),
                         '''references''': datasets.Value('''string''' ,   id='''sequence'''     ),
                     }     ) ,   codebase_urls=['''https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'''] ,   reference_urls=[
                     '''https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score''',
                     '''https://en.wikipedia.org/wiki/METEOR''',
                 ] ,   )

       def     __UpperCamelCase     (							self ,   lowercase__     ):







             '''simple docstring'''



             import nltk

             nltk.download('''wordnet'''     )
             if NLTK_VERSION >= version.Version('''3.6.5'''     ):
                   nltk.download('''punkt'''     )
             if NLTK_VERSION >= version.Version('''3.6.6'''     ):
                   nltk.download('''omw-1.4'''     )


       def     __UpperCamelCase     (							self ,   lowercase__ ,   lowercase__ ,   lowercase__=0.9 ,   lowercase__=3 ,   lowercase__=0.5     ):







             '''simple docstring'''



             if NLTK_VERSION >= version.Version('''3.6.5'''     ):
                   __A    =[
                       meteor_score.single_meteor_score(
                           word_tokenize(lowercase__     ) ,   word_tokenize(lowercase__     ) ,   alpha=lowercase__ ,   beta=lowercase__ ,   gamma=lowercase__     )
                       for ref, pred in zip(lowercase__ ,   lowercase__     )
                   ]
             else:
                   __A    =[
                       meteor_score.single_meteor_score(lowercase__ ,   lowercase__ ,   alpha=lowercase__ ,   beta=lowercase__ ,   gamma=lowercase__     )
                       for ref, pred in zip(lowercase__ ,   lowercase__     )
                   ]

             return {"meteor": np.mean(lowercase__     )}


