






"""simple docstring"""





import collections
import inspect
import unittest

from transformers import FocalNetConfig
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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import (
      FocalNetBackbone,
      FocalNetForImageClassification,
      FocalNetForMaskedImageModeling,
      FocalNetModel,
  )
  from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor






class      a						:






    def __init__(       self     :							Union[str, Any]       ,						__SCREAMING_SNAKE_CASE     :							int       ,						__SCREAMING_SNAKE_CASE     :							Optional[int]=13       ,						__SCREAMING_SNAKE_CASE     :							List[str]=32       ,						__SCREAMING_SNAKE_CASE     :							List[str]=2       ,						__SCREAMING_SNAKE_CASE     :							List[Any]=3       ,						__SCREAMING_SNAKE_CASE     :							str=16       ,						__SCREAMING_SNAKE_CASE     :							Union[str, Any]=[32, 64, 128]       ,						__SCREAMING_SNAKE_CASE     :							Dict=[1, 2, 1]       ,						__SCREAMING_SNAKE_CASE     :							List[Any]=[2, 2, 4]       ,						__SCREAMING_SNAKE_CASE     :							int=2       ,						__SCREAMING_SNAKE_CASE     :							List[str]=2.0       ,						__SCREAMING_SNAKE_CASE     :							List[str]=True       ,						__SCREAMING_SNAKE_CASE     :							List[str]=0.0       ,						__SCREAMING_SNAKE_CASE     :							str=0.0       ,						__SCREAMING_SNAKE_CASE     :							List[str]=0.1       ,						__SCREAMING_SNAKE_CASE     :							Tuple="gelu"       ,						__SCREAMING_SNAKE_CASE     :							int=False       ,						__SCREAMING_SNAKE_CASE     :							List[str]=True       ,						__SCREAMING_SNAKE_CASE     :							str=0.02       ,						__SCREAMING_SNAKE_CASE     :							int=1e-5       ,						__SCREAMING_SNAKE_CASE     :							Optional[Any]=True       ,						__SCREAMING_SNAKE_CASE     :							List[str]=None       ,						__SCREAMING_SNAKE_CASE     :							Dict=True       ,						__SCREAMING_SNAKE_CASE     :							Optional[Any]=10       ,						__SCREAMING_SNAKE_CASE     :							Optional[int]=8       ,						__SCREAMING_SNAKE_CASE     :							str=["stage1", "stage2"]       ,						__SCREAMING_SNAKE_CASE     :							List[str]=[1, 2]       ,						)     ->		List[Any]:
      lowerCamelCase_         =						parent
      lowerCamelCase_         =						batch_size
      lowerCamelCase_         =						image_size
      lowerCamelCase_         =						patch_size
      lowerCamelCase_         =						num_channels
      lowerCamelCase_         =						embed_dim
      lowerCamelCase_         =						hidden_sizes
      lowerCamelCase_         =						depths
      lowerCamelCase_         =						num_heads
      lowerCamelCase_         =						window_size
      lowerCamelCase_         =						mlp_ratio
      lowerCamelCase_         =						qkv_bias
      lowerCamelCase_         =						hidden_dropout_prob
      lowerCamelCase_         =						attention_probs_dropout_prob
      lowerCamelCase_         =						drop_path_rate
      lowerCamelCase_         =						hidden_act
      lowerCamelCase_         =						use_absolute_embeddings
      lowerCamelCase_         =						patch_norm
      lowerCamelCase_         =						layer_norm_eps
      lowerCamelCase_         =						initializer_range
      lowerCamelCase_         =						is_training
      lowerCamelCase_         =						scope
      lowerCamelCase_         =						use_labels
      lowerCamelCase_         =						type_sequence_label_size
      lowerCamelCase_         =						encoder_stride
      lowerCamelCase_         =						out_features
      lowerCamelCase_         =						out_indices






    def    UpperCamelCase       (       self     :							List[str]					)     ->		Tuple:
      lowerCamelCase_         =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

      lowerCamelCase_         =						self.get_config()

      return config, pixel_values, labels






    def    UpperCamelCase       (       self     :							List[str]					)     ->		int:
      return FocalNetConfig(
          image_size=self.image_size       ,						patch_size=self.patch_size       ,						num_channels=self.num_channels       ,						embed_dim=self.embed_dim       ,						hidden_sizes=self.hidden_sizes       ,						depths=self.depths       ,						num_heads=self.num_heads       ,						window_size=self.window_size       ,						mlp_ratio=self.mlp_ratio       ,						qkv_bias=self.qkv_bias       ,						hidden_dropout_prob=self.hidden_dropout_prob       ,						attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,						drop_path_rate=self.drop_path_rate       ,						hidden_act=self.hidden_act       ,						use_absolute_embeddings=self.use_absolute_embeddings       ,						path_norm=self.patch_norm       ,						layer_norm_eps=self.layer_norm_eps       ,						initializer_range=self.initializer_range       ,						encoder_stride=self.encoder_stride       ,						out_features=self.out_features       ,						out_indices=self.out_indices       ,						)






    def    UpperCamelCase       (       self     :							str       ,						__SCREAMING_SNAKE_CASE     :							Optional[Any]       ,						__SCREAMING_SNAKE_CASE     :							List[Any]       ,						__SCREAMING_SNAKE_CASE     :							int					)     ->		Optional[int]:
      lowerCamelCase_         =						FocalNetModel(config=__SCREAMING_SNAKE_CASE					)
      model.to(__SCREAMING_SNAKE_CASE					)
      model.eval()
      lowerCamelCase_         =						model(__SCREAMING_SNAKE_CASE					)

      lowerCamelCase_         =						((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths					) - 1))
      lowerCamelCase_         =						int(config.embed_dim * 2 ** (len(config.depths					) - 1)					)

      self.parent.assertEqual(result.last_hidden_state.shape       ,						(self.batch_size, expected_seq_len, expected_dim)					)






    def    UpperCamelCase       (       self     :							Optional[int]       ,						__SCREAMING_SNAKE_CASE     :							Tuple       ,						__SCREAMING_SNAKE_CASE     :							Optional[Any]       ,						__SCREAMING_SNAKE_CASE     :							Dict					)     ->		List[Any]:
      lowerCamelCase_         =						FocalNetBackbone(config=__SCREAMING_SNAKE_CASE					)
      model.to(__SCREAMING_SNAKE_CASE					)
      model.eval()
      lowerCamelCase_         =						model(__SCREAMING_SNAKE_CASE					)

      # verify feature maps
      self.parent.assertEqual(len(result.feature_maps					)       ,						len(config.out_features					)					)
      self.parent.assertListEqual(list(result.feature_maps[0].shape					)       ,						[self.batch_size, self.image_size, 8, 8]					)

      # 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
      lowerCamelCase_         =						None
      lowerCamelCase_         =						FocalNetBackbone(config=__SCREAMING_SNAKE_CASE					)
      model.to(__SCREAMING_SNAKE_CASE					)
      model.eval()
      lowerCamelCase_         =						model(__SCREAMING_SNAKE_CASE					)

      # verify feature maps
      self.parent.assertEqual(len(result.feature_maps					)       ,						1					)
      self.parent.assertListEqual(list(result.feature_maps[0].shape					)       ,						[self.batch_size, self.image_size * 2, 4, 4]					)

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






    def    UpperCamelCase       (       self     :							Optional[Any]       ,						__SCREAMING_SNAKE_CASE     :							Union[str, Any]       ,						__SCREAMING_SNAKE_CASE     :							str       ,						__SCREAMING_SNAKE_CASE     :							Optional[Any]					)     ->		Optional[int]:
      lowerCamelCase_         =						FocalNetForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE					)
      model.to(__SCREAMING_SNAKE_CASE					)
      model.eval()
      lowerCamelCase_         =						model(__SCREAMING_SNAKE_CASE					)
      self.parent.assertEqual(
          result.reconstruction.shape       ,						(self.batch_size, self.num_channels, self.image_size, self.image_size)					)

      # test greyscale images
      lowerCamelCase_         =						1
      lowerCamelCase_         =						FocalNetForMaskedImageModeling(__SCREAMING_SNAKE_CASE					)
      model.to(__SCREAMING_SNAKE_CASE					)
      model.eval()

      lowerCamelCase_         =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
      lowerCamelCase_         =						model(__SCREAMING_SNAKE_CASE					)
      self.parent.assertEqual(result.reconstruction.shape       ,						(self.batch_size, 1, self.image_size, self.image_size)					)






    def    UpperCamelCase       (       self     :							Optional[int]       ,						__SCREAMING_SNAKE_CASE     :							str       ,						__SCREAMING_SNAKE_CASE     :							Any       ,						__SCREAMING_SNAKE_CASE     :							List[Any]					)     ->		int:
      lowerCamelCase_         =						self.type_sequence_label_size
      lowerCamelCase_         =						FocalNetForImageClassification(__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.type_sequence_label_size)					)

      # test greyscale images
      lowerCamelCase_         =						1
      lowerCamelCase_         =						FocalNetForImageClassification(__SCREAMING_SNAKE_CASE					)
      model.to(__SCREAMING_SNAKE_CASE					)
      model.eval()

      lowerCamelCase_         =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
      lowerCamelCase_         =						model(__SCREAMING_SNAKE_CASE					)
      self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.type_sequence_label_size)					)






    def    UpperCamelCase       (       self     :							Optional[Any]					)     ->		Dict:
      lowerCamelCase_         =						self.prepare_config_and_inputs()

      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						:     Dict						= (
        (
            FocalNetModel,
            FocalNetForImageClassification,
            FocalNetForMaskedImageModeling,
            FocalNetBackbone,
        )
        if is_torch_available()
        else ()
    )
    SCREAMING_SNAKE_CASE						:     Dict						= (
        {"""feature-extraction""": FocalNetModel, """image-classification""": FocalNetForImageClassification}
        if is_torch_available()
        else {}
    )
    SCREAMING_SNAKE_CASE						:     Dict						= False

    SCREAMING_SNAKE_CASE						:     Dict						= False
    SCREAMING_SNAKE_CASE						:     Dict						= False
    SCREAMING_SNAKE_CASE						:     List[str]						= False
    SCREAMING_SNAKE_CASE						:     Tuple						= False






    def    UpperCamelCase       (       self     :							List[Any]					)     ->		Dict:
      lowerCamelCase_         =						FocalNetModelTester(self					)
      lowerCamelCase_         =						ConfigTester(self       ,						config_class=__SCREAMING_SNAKE_CASE       ,						embed_dim=37       ,						has_text_modality=__SCREAMING_SNAKE_CASE					)






    def    UpperCamelCase       (       self     :							str					)     ->		Union[str, Any]:
      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    UpperCamelCase       (       self     :							Dict					)     ->		int:
      return






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






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






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






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






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






    @unittest.skip(reason='FocalNet does not use feedforward chunking'					)
    def    UpperCamelCase       (       self     :							Optional[Any]					)     ->		Optional[int]:
      pass






    def    UpperCamelCase       (       self     :							Any					)     ->		List[str]:
      lowerCamelCase_     ,	lowerCamelCase_         =						self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes[:-1]:
        lowerCamelCase_         =						model_class(__SCREAMING_SNAKE_CASE					)
        self.assertIsInstance(model.get_input_embeddings()       ,						(nn.Module)					)
        lowerCamelCase_         =						model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE       ,						nn.Linear					)					)






    def    UpperCamelCase       (       self     :							int					)     ->		List[Any]:
      lowerCamelCase_     ,	lowerCamelCase_         =						self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes[:-1]:
        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     :							Optional[int]       ,						__SCREAMING_SNAKE_CASE     :							int       ,						__SCREAMING_SNAKE_CASE     :							Optional[Any]       ,						__SCREAMING_SNAKE_CASE     :							List[str]       ,						__SCREAMING_SNAKE_CASE     :							Dict					)     ->		Optional[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_         =						getattr(
          self.model_tester       ,						'expected_num_hidden_layers'       ,						len(self.model_tester.depths					) + 1					)
      self.assertEqual(len(__SCREAMING_SNAKE_CASE					)       ,						__SCREAMING_SNAKE_CASE					)

      # FocalNet has a different seq_length
      lowerCamelCase_         =						(
          config.patch_size
          if isinstance(config.patch_size       ,						collections.abc.Iterable					)
          else (config.patch_size, config.patch_size)
      )

      lowerCamelCase_         =						(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

      self.assertListEqual(
          list(hidden_states[0].shape[-2:]					)       ,						[num_patches, self.model_tester.embed_dim]       ,						)

      lowerCamelCase_         =						outputs.reshaped_hidden_states
      self.assertEqual(len(__SCREAMING_SNAKE_CASE					)       ,						__SCREAMING_SNAKE_CASE					)

      lowerCamelCase_     ,	lowerCamelCase_     ,	lowerCamelCase_     ,	lowerCamelCase_         =						reshaped_hidden_states[0].shape
      lowerCamelCase_         =						(
          reshaped_hidden_states[0].view(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						height * width					).permute(0       ,						2       ,						1					)
      )
      self.assertListEqual(
          list(reshaped_hidden_states.shape[-2:]					)       ,						[num_patches, self.model_tester.embed_dim]       ,						)






    def    UpperCamelCase       (       self     :							Optional[Any]					)     ->		Tuple:
      lowerCamelCase_     ,	lowerCamelCase_         =						self.model_tester.prepare_config_and_inputs_for_common()

      lowerCamelCase_         =						(
          self.model_tester.image_size
          if isinstance(self.model_tester.image_size       ,						collections.abc.Iterable					)
          else (self.model_tester.image_size, self.model_tester.image_size)
      )

      for model_class in self.all_model_classes[:-1]:
        lowerCamelCase_         =						True
        self.check_hidden_states_output(__SCREAMING_SNAKE_CASE       ,						__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

        self.check_hidden_states_output(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					)






    def    UpperCamelCase       (       self     :							Union[str, Any]					)     ->		List[Any]:
      lowerCamelCase_     ,	lowerCamelCase_         =						self.model_tester.prepare_config_and_inputs_for_common()
      lowerCamelCase_         =						3

      lowerCamelCase_         =						(
          self.model_tester.image_size
          if isinstance(self.model_tester.image_size       ,						collections.abc.Iterable					)
          else (self.model_tester.image_size, self.model_tester.image_size)
      )
      lowerCamelCase_         =						(
          config.patch_size
          if isinstance(config.patch_size       ,						collections.abc.Iterable					)
          else (config.patch_size, config.patch_size)
      )

      lowerCamelCase_         =						image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
      lowerCamelCase_         =						image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

      for model_class in self.all_model_classes[:-1]:
        lowerCamelCase_         =						True
        self.check_hidden_states_output(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						(padded_height, padded_width)					)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        lowerCamelCase_         =						True
        self.check_hidden_states_output(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						(padded_height, padded_width)					)






    @slow
    def    UpperCamelCase       (       self     :							Optional[int]					)     ->		Any:
      for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCamelCase_         =						FocalNetModel.from_pretrained(__SCREAMING_SNAKE_CASE					)
        self.assertIsNotNone(__SCREAMING_SNAKE_CASE					)






    def    UpperCamelCase       (       self     :							List[Any]					)     ->		str:
      lowerCamelCase_     ,	lowerCamelCase_         =						self.model_tester.prepare_config_and_inputs_for_common()

      lowerCamelCase_         =						_config_zero_init(__SCREAMING_SNAKE_CASE					)
      for model_class in self.all_model_classes:
        lowerCamelCase_         =						model_class(config=__SCREAMING_SNAKE_CASE					)
        for name, param in model.named_parameters():
          if "embeddings" not in name and param.requires_grad:
            self.assertIn(
                ((param.data.mean() * 1e9).round() / 1e9).item()       ,						[0.0, 1.0]       ,						msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''       ,						)






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






    @cached_property
    def    UpperCamelCase       (       self     :							List[Any]					)     ->		int:
      # TODO update organization
      return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'					) if is_vision_available() else None






    @slow
    def    UpperCamelCase       (       self     :							Optional[int]					)     ->		Tuple:
      lowerCamelCase_         =						FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'					).to(__SCREAMING_SNAKE_CASE					)
      lowerCamelCase_         =						self.default_image_processor

      lowerCamelCase_         =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
      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, 1000)					)
      self.assertEqual(outputs.logits.shape       ,						__SCREAMING_SNAKE_CASE					)
      lowerCamelCase_         =						torch.tensor([0.2_166, -0.4_368, 0.2_191]					).to(__SCREAMING_SNAKE_CASE					)
      self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,						__SCREAMING_SNAKE_CASE       ,						atol=1e-4					)					)
      self.assertTrue(outputs.logits.argmax(dim=-1					).item()       ,						281					)






@require_torch
class      a						(					__snake_case  ,      unittest.TestCase		):
    SCREAMING_SNAKE_CASE						:     List[str]						= (FocalNetBackbone,) if is_torch_available() else ()
    SCREAMING_SNAKE_CASE						:     List[Any]						= FocalNetConfig

    SCREAMING_SNAKE_CASE						:     int						= False






    def    UpperCamelCase       (       self     :							Tuple					)     ->		Any:
      lowerCamelCase_         =						FocalNetModelTester(self					)












"""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					)}




