






"""simple docstring"""





import inspect
import unittest

from transformers import MobileNetVaConfig
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_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 MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
  from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import MobileNetVaImageProcessor






class      a						(					__snake_case		):






    def    UpperCamelCase       (       self     :							List[str]					)     ->		Dict:
      lowerCamelCase_         =						self.config_class(**self.inputs_dict					)
      self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE       ,						'tf_padding'					)					)
      self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE       ,						'depth_multiplier'					)					)






class      a						:






    def __init__(       self     :							int       ,						__SCREAMING_SNAKE_CASE     :							Dict       ,						__SCREAMING_SNAKE_CASE     :							Union[str, Any]=13       ,						__SCREAMING_SNAKE_CASE     :							int=3       ,						__SCREAMING_SNAKE_CASE     :							int=32       ,						__SCREAMING_SNAKE_CASE     :							Optional[int]=0.25       ,						__SCREAMING_SNAKE_CASE     :							str=8       ,						__SCREAMING_SNAKE_CASE     :							Any=8       ,						__SCREAMING_SNAKE_CASE     :							Tuple=6       ,						__SCREAMING_SNAKE_CASE     :							str=32       ,						__SCREAMING_SNAKE_CASE     :							Union[str, Any]=True       ,						__SCREAMING_SNAKE_CASE     :							Union[str, Any]=True       ,						__SCREAMING_SNAKE_CASE     :							Tuple=True       ,						__SCREAMING_SNAKE_CASE     :							Dict="relu6"       ,						__SCREAMING_SNAKE_CASE     :							List[str]=1280       ,						__SCREAMING_SNAKE_CASE     :							int=0.1       ,						__SCREAMING_SNAKE_CASE     :							Optional[Any]=0.02       ,						__SCREAMING_SNAKE_CASE     :							Optional[int]=True       ,						__SCREAMING_SNAKE_CASE     :							Any=True       ,						__SCREAMING_SNAKE_CASE     :							List[Any]=10       ,						__SCREAMING_SNAKE_CASE     :							List[str]=None       ,						)     ->		int:
      lowerCamelCase_         =						parent
      lowerCamelCase_         =						batch_size
      lowerCamelCase_         =						num_channels
      lowerCamelCase_         =						image_size
      lowerCamelCase_         =						depth_multiplier
      lowerCamelCase_         =						depth_divisible_by
      lowerCamelCase_         =						min_depth
      lowerCamelCase_         =						expand_ratio
      lowerCamelCase_         =						tf_padding
      lowerCamelCase_         =						output_stride
      lowerCamelCase_         =						first_layer_is_expansion
      lowerCamelCase_         =						finegrained_output
      lowerCamelCase_         =						hidden_act
      lowerCamelCase_         =						last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier					)
      lowerCamelCase_         =						classifier_dropout_prob
      lowerCamelCase_         =						use_labels
      lowerCamelCase_         =						is_training
      lowerCamelCase_         =						num_labels
      lowerCamelCase_         =						initializer_range
      lowerCamelCase_         =						scope






    def    UpperCamelCase       (       self     :							Optional[int]					)     ->		Optional[Any]:
      lowerCamelCase_         =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

      lowerCamelCase_         =						self.get_config()

      return config, pixel_values, labels, pixel_labels






    def    UpperCamelCase       (       self     :							Tuple					)     ->		Any:
      return MobileNetVaConfig(
          num_channels=self.num_channels       ,						image_size=self.image_size       ,						depth_multiplier=self.depth_multiplier       ,						depth_divisible_by=self.depth_divisible_by       ,						min_depth=self.min_depth       ,						expand_ratio=self.expand_ratio       ,						output_stride=self.output_stride       ,						first_layer_is_expansion=self.first_layer_is_expansion       ,						finegrained_output=self.finegrained_output       ,						hidden_act=self.hidden_act       ,						tf_padding=self.tf_padding       ,						classifier_dropout_prob=self.classifier_dropout_prob       ,						initializer_range=self.initializer_range       ,						)






    def    UpperCamelCase       (       self     :							Tuple       ,						__SCREAMING_SNAKE_CASE     :							Tuple       ,						__SCREAMING_SNAKE_CASE     :							Tuple       ,						__SCREAMING_SNAKE_CASE     :							Optional[int]       ,						__SCREAMING_SNAKE_CASE     :							Tuple					)     ->		Optional[Any]:
      lowerCamelCase_         =						MobileNetVaModel(config=__SCREAMING_SNAKE_CASE					)
      model.to(__SCREAMING_SNAKE_CASE					)
      model.eval()
      lowerCamelCase_         =						model(__SCREAMING_SNAKE_CASE					)
      self.parent.assertEqual(
          result.last_hidden_state.shape       ,						(
              self.batch_size,
              self.last_hidden_size,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )       ,						)
      self.parent.assertEqual(
          result.pooler_output.shape       ,						(self.batch_size, self.last_hidden_size)       ,						)






    def    UpperCamelCase       (       self     :							Optional[Any]       ,						__SCREAMING_SNAKE_CASE     :							Optional[Any]       ,						__SCREAMING_SNAKE_CASE     :							List[Any]       ,						__SCREAMING_SNAKE_CASE     :							int       ,						__SCREAMING_SNAKE_CASE     :							Tuple					)     ->		str:
      lowerCamelCase_         =						self.num_labels
      lowerCamelCase_         =						MobileNetVaForImageClassification(__SCREAMING_SNAKE_CASE					)
      model.to(__SCREAMING_SNAKE_CASE					)
      model.eval()
      lowerCamelCase_         =						model(__SCREAMING_SNAKE_CASE       ,						labels=__SCREAMING_SNAKE_CASE					)
      self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.num_labels)					)






    def    UpperCamelCase       (       self     :							Tuple       ,						__SCREAMING_SNAKE_CASE     :							str       ,						__SCREAMING_SNAKE_CASE     :							Union[str, Any]       ,						__SCREAMING_SNAKE_CASE     :							List[str]       ,						__SCREAMING_SNAKE_CASE     :							str					)     ->		Dict:
      lowerCamelCase_         =						self.num_labels
      lowerCamelCase_         =						MobileNetVaForSemanticSegmentation(__SCREAMING_SNAKE_CASE					)
      model.to(__SCREAMING_SNAKE_CASE					)
      model.eval()
      lowerCamelCase_         =						model(__SCREAMING_SNAKE_CASE					)
      self.parent.assertEqual(
          result.logits.shape       ,						(
              self.batch_size,
              self.num_labels,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )       ,						)
      lowerCamelCase_         =						model(__SCREAMING_SNAKE_CASE       ,						labels=__SCREAMING_SNAKE_CASE					)
      self.parent.assertEqual(
          result.logits.shape       ,						(
              self.batch_size,
              self.num_labels,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )       ,						)






    def    UpperCamelCase       (       self     :							Optional[Any]					)     ->		List[str]:
      lowerCamelCase_         =						self.prepare_config_and_inputs()
      lowerCamelCase_     ,	lowerCamelCase_     ,	lowerCamelCase_     ,	lowerCamelCase_         =						config_and_inputs
      lowerCamelCase_         =						{'pixel_values': pixel_values}
      return config, inputs_dict






@require_torch
class      a						(					__snake_case  ,      __snake_case  ,      unittest.TestCase		):
    SCREAMING_SNAKE_CASE						:     List[Any]						= (
        (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
        if is_torch_available()
        else ()
    )
    SCREAMING_SNAKE_CASE						:     Union[str, Any]						= (
        {
            """feature-extraction""": MobileNetVaModel,
            """image-classification""": MobileNetVaForImageClassification,
            """image-segmentation""": MobileNetVaForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    SCREAMING_SNAKE_CASE						:     str						= False
    SCREAMING_SNAKE_CASE						:     str						= False
    SCREAMING_SNAKE_CASE						:     Any						= False
    SCREAMING_SNAKE_CASE						:     Optional[Any]						= False






    def    UpperCamelCase       (       self     :							int					)     ->		Dict:
      lowerCamelCase_         =						MobileNetVaModelTester(self					)
      lowerCamelCase_         =						MobileNetVaConfigTester(self       ,						config_class=__SCREAMING_SNAKE_CASE       ,						has_text_modality=__SCREAMING_SNAKE_CASE					)






    def    UpperCamelCase       (       self     :							Any					)     ->		List[str]:
      self.config_tester.run_common_tests()






    @unittest.skip(reason='MobileNetV2 does not use inputs_embeds'					)
    def    UpperCamelCase       (       self     :							Any					)     ->		Optional[Any]:
      pass






    @unittest.skip(reason='MobileNetV2 does not support input and output embeddings'					)
    def    UpperCamelCase       (       self     :							int					)     ->		Union[str, Any]:
      pass






    @unittest.skip(reason='MobileNetV2 does not output attentions'					)
    def    UpperCamelCase       (       self     :							List[str]					)     ->		Optional[Any]:
      pass






    def    UpperCamelCase       (       self     :							Dict					)     ->		int:
      lowerCamelCase_     ,	lowerCamelCase_         =						self.model_tester.prepare_config_and_inputs_for_common()

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

        lowerCamelCase_         =						['pixel_values']
        self.assertListEqual(arg_names[:1]       ,						__SCREAMING_SNAKE_CASE					)






    def    UpperCamelCase       (       self     :							Tuple					)     ->		int:
      lowerCamelCase_         =						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE					)






    def    UpperCamelCase       (       self     :							Optional[Any]					)     ->		Tuple:
      def check_hidden_states_output(__SCREAMING_SNAKE_CASE     :							Union[str, Any]       ,						__SCREAMING_SNAKE_CASE     :							List[str]       ,						__SCREAMING_SNAKE_CASE     :							int					):
        lowerCamelCase_         =						model_class(__SCREAMING_SNAKE_CASE					)
        model.to(__SCREAMING_SNAKE_CASE					)
        model.eval()

        with torch.no_grad():
          lowerCamelCase_         =						model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					)					)

        lowerCamelCase_         =						outputs.hidden_states

        lowerCamelCase_         =						16
        self.assertEqual(len(__SCREAMING_SNAKE_CASE					)       ,						__SCREAMING_SNAKE_CASE					)

      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(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					)

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

        check_hidden_states_output(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					)






    def    UpperCamelCase       (       self     :							Dict					)     ->		List[str]:
      lowerCamelCase_         =						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE					)






    def    UpperCamelCase       (       self     :							str					)     ->		Optional[int]:
      lowerCamelCase_         =						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE					)






    @slow
    def    UpperCamelCase       (       self     :							str					)     ->		str:
      for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCamelCase_         =						MobileNetVaModel.from_pretrained(__SCREAMING_SNAKE_CASE					)
        self.assertIsNotNone(__SCREAMING_SNAKE_CASE					)







def      lowerCamelCase__       (							)      ->				Optional[int]:
  lowerCamelCase_         =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
  return image






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






    @cached_property
    def    UpperCamelCase       (       self     :							Optional[int]					)     ->		str:
      return (
          MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224'					) if is_vision_available() else None
      )






    @slow
    def    UpperCamelCase       (       self     :							Union[str, Any]					)     ->		Optional[Any]:
      lowerCamelCase_         =						MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224'					).to(__SCREAMING_SNAKE_CASE					)

      lowerCamelCase_         =						self.default_image_processor
      lowerCamelCase_         =						prepare_img()
      lowerCamelCase_         =						image_processor(images=__SCREAMING_SNAKE_CASE       ,						return_tensors='pt'					).to(__SCREAMING_SNAKE_CASE					)

      # forward pass
      with torch.no_grad():
        lowerCamelCase_         =						model(**__SCREAMING_SNAKE_CASE					)

      # verify the logits
      lowerCamelCase_         =						torch.Size((1, 1001)					)
      self.assertEqual(outputs.logits.shape       ,						__SCREAMING_SNAKE_CASE					)

      lowerCamelCase_         =						torch.tensor([0.2_445, -1.1_993, 0.1_905]					).to(__SCREAMING_SNAKE_CASE					)

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






    @slow
    def    UpperCamelCase       (       self     :							Optional[int]					)     ->		Any:
      lowerCamelCase_         =						MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'					)
      lowerCamelCase_         =						model.to(__SCREAMING_SNAKE_CASE					)

      lowerCamelCase_         =						MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'					)

      lowerCamelCase_         =						prepare_img()
      lowerCamelCase_         =						image_processor(images=__SCREAMING_SNAKE_CASE       ,						return_tensors='pt'					).to(__SCREAMING_SNAKE_CASE					)

      # forward pass
      with torch.no_grad():
        lowerCamelCase_         =						model(**__SCREAMING_SNAKE_CASE					)
      lowerCamelCase_         =						outputs.logits

      # verify the logits
      lowerCamelCase_         =						torch.Size((1, 21, 65, 65)					)
      self.assertEqual(logits.shape       ,						__SCREAMING_SNAKE_CASE					)

      lowerCamelCase_         =						torch.tensor(
          [
              [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]],
              [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]],
              [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]],
          ]       ,						device=__SCREAMING_SNAKE_CASE       ,						)

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












"""simple docstring"""





import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


_SCREAMING_SNAKE_CASE					:				Tuple					    =						version.parse(importlib_metadata.version('''nltk'''))
if NLTK_VERSION >= version.Version('''3.6.4'''):
  from nltk import word_tokenize


_SCREAMING_SNAKE_CASE					:				Tuple					    =						'''\
@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},
}
'''

_SCREAMING_SNAKE_CASE					:				int					    =						'''\
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.
'''

_SCREAMING_SNAKE_CASE					:				List[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      a						(					datasets.Metric		):






    def    UpperCamelCase       (       self     :							List[str]					)     ->		List[str]:
      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     :							Optional[int]       ,						__SCREAMING_SNAKE_CASE     :							Union[str, Any]					)     ->		Dict:
      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     :							Optional[int]       ,						__SCREAMING_SNAKE_CASE     :							Any       ,						__SCREAMING_SNAKE_CASE     :							Any       ,						__SCREAMING_SNAKE_CASE     :							List[Any]=0.9       ,						__SCREAMING_SNAKE_CASE     :							Dict=3       ,						__SCREAMING_SNAKE_CASE     :							Union[str, Any]=0.5					)     ->		int:
      if NLTK_VERSION >= version.Version('3.6.5'					):
        lowerCamelCase_         =						[
            meteor_score.single_meteor_score(
                word_tokenize(__SCREAMING_SNAKE_CASE					)       ,						word_tokenize(__SCREAMING_SNAKE_CASE					)       ,						alpha=__SCREAMING_SNAKE_CASE       ,						beta=__SCREAMING_SNAKE_CASE       ,						gamma=__SCREAMING_SNAKE_CASE					)
            for ref, pred in zip(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					)
        ]
      else:
        lowerCamelCase_         =						[
            meteor_score.single_meteor_score(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						alpha=__SCREAMING_SNAKE_CASE       ,						beta=__SCREAMING_SNAKE_CASE       ,						gamma=__SCREAMING_SNAKE_CASE					)
            for ref, pred in zip(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					)
        ]

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




